IHttpModule和IHttpHandler

一、IHttpModule

  • IHttpModule的作用
    • 可在IIS与asp.net的集成管道事件中注册自定义事件处理程序
    • MVC就是利用UrlRoutingModule在PostResolveRequestCache管道事件中注册事件处理程序,对满足路由匹配的请求进行拦截并转入到MvcHandler中进行处理
  • 自定义IHttpModule
public class CustomModule : IHttpModule
{
    public void Dispose()
    {
        
    }

    public void Init(HttpApplication context)
    {
        context.PostAcquireRequestState += (sender, e) =>
        {
            //TODO:..
        };
    }
}
  • IHttpModule注册
<configuration>
  <system.webServer>
    <modules>
      <add name="customModule" type="XXX.CustomModule"/>
    </modules>
  </system.webServer>
</configuration>
  • 应用场景
    • 可对所有类型的请求进行处理
    • 授权认证、日志记录等
    • 针对授权认证
      • IAuthenticationFilter也可进行授权认证,但只能针对MVC请求

二、IHttpHandler

  • IHttpHandler的作用
    • 处理特定类型的请求
  • 自定义IHttpHandler
public class CustomHandler : IHttpHandler
{
    public bool IsReusable => true;

    public void ProcessRequest(HttpContext context)
    {
        //TODO:
    }
}
  • IHttpHandler注册
<configuration>
  <system.webServer>
    <handlers>
      <add name="1" path="*.1" verb="*" type="XXX.CustomHandler"/>
    </handlers>
  </system.webServer>
</configuration>
  • 为了使自定义Handler生效,需要跳过MVC路由
    • 在进行路由匹配时,会先判断请求的路径是否是服务器上存在的文件或者文件夹,如果是则跳过路由匹配,这也就意味着不需要MVC进行处理
    • 如果不是存在的文件或文件夹,则基本上都能匹配上默认的路由模板
public static void RegisterRoutes(RouteCollection routes)
{
    routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
    routes.IgnoreRoute("{resource}.1/{*pathInfo}");

    routes.MapRoute(
        name: "Default",
        url: "{controller}/{action}/{id}",
        defaults: new { controller = "Login", action = "Index", id = UrlParameter.Optional }
    );
}
  • 路由匹配的部分源代码
    • 主要利用的是HttpRequest的属性AppRelativeCurrentExecutionFilePath
    • 当前请求相对于应用程序根的虚拟路径
    • 当Url为"http://localhost:8080/1.png"时, AppRelativeCurrentExecutionFilePath= “~/1.png”

在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值