码迷,mamicode.com
首页 > 其他好文 > 详细

如何使用请求管道中事件实现自定义方法

时间:2016-08-02 20:41:10      阅读:134      评论:0      收藏:0      [点我收藏+]

标签:

1.新建类xx.cs:IHttpModule,继承该接口,实现接口方法

public class ValidateSessionHttpModule : IHttpModule
    {
        public void Dispose()
        {
            throw new NotImplementedException();
        }

        /// <summary>
        /// 完成请求管道中事件的注册
        /// </summary>
        /// <param name="context"></param>
        public void Init(HttpApplication context)
        {
            //throw new NotImplementedException();
            //给事件注册方法,当事件被触发时候执行
            context.AcquireRequestState += Context_AcquireRequestState;
        }

        private void Context_AcquireRequestState(object sender, EventArgs e)
        {
            //throw new NotImplementedException();
            HttpApplication application = sender as HttpApplication;
            HttpContext context = application.Context;
            string url = context.Request.Url.ToString();
            if (url.Contains("Admin"))
            {
                if (context.Session["key"] == null)
                {
                    context.Response.Redirect("/Login.aspx");
                }
            }
        }
    }

2.或者在Global文件的相应方法中写自己的代码

 public class Global : System.Web.HttpApplication
    {
        /// <summary>
        /// Web应用程序第一次启动时候调用的方法,并且只被调用一次
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void Application_Start(object sender, EventArgs e)
        {
            #region 定时任务框架

            #endregion
        }

        /// <summary>
        /// 会话开始时候调用,可以用来通过Application统计总访问人数
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void Session_Start(object sender, EventArgs e)
        {

        }

        protected void Application_BeginRequest(object sender, EventArgs e)
        {

        }

        protected void Application_AuthenticateRequest(object sender, EventArgs e)
        {

        }

        /// <summary>
        /// 全局的异常处理点,如果程序中有trycache则不调用该方法
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void Application_Error(object sender, EventArgs e)
        {
            //获取异常信息
            Exception ex = HttpContext.Current.Server.GetLastError();
            //Log4Net写日志
        }

        protected void Session_End(object sender, EventArgs e)
        {

        }

        protected void Application_End(object sender, EventArgs e)
        {

        }
    }

 

如何使用请求管道中事件实现自定义方法

标签:

原文地址:http://www.cnblogs.com/xtxtx/p/5730489.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!