自定义HttpModule实现某些功能的例子

来源:互联网 发布:java throw try catch 编辑:程序博客网 时间:2024/06/05 10:24

        在执行用户请求的时候可能会有一些特殊的要求例如验证用户是否登录,URL重写等。这些问题需要在执行常规代码之前执行,这里就用到了自定义HttpModules。具体的使用方法如下:

       自定义一个类  :

 

using System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Threading.Tasks;using System.Web;namespace Project.Common{    //过滤器。   public class CheckSessionModule:IHttpModule    {        public void Dispose()        {            throw new NotImplementedException();        }        public void Init(HttpApplication context)        {            //URL重写。           context.AcquireRequestState+=context_AcquireRequestState;        }        public void context_AcquireRequestState(object sender, EventArgs e)        {            //判断Session是否有值.            HttpApplication application = (HttpApplication)sender;            HttpContext context = application.Context;            string url = context.Request.Url.ToString();//获取用户请求的URL地址.            if (url.Contains("AdminManger"))            {                if (context.Session["userInfo"] == null)                {                    context.Response.Redirect("要跳转的页面");                }            }        }    }}

 在WebConfig文件中对自定义的HttpModule类进行注册


<system.webServer>    <modules>      <add name="CheckSessionModule" type="Project.Common.CheckSessionModule"/>    </modules>  </system.webServer>

这样  在HttpApplication 调用InitModules方法的时候就会注册我们自己定义的事件  实现相应的功能



0 0