一、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) =>
{
};
}
}
<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)
{
}
}
<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”