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

        在执行用户请求的时候可能会有一些特殊的要求例如验证用户是否登录,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方法的时候就会注册我们自己定义的事件  实现相应的功能

 


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值