个人IHttpHandler,IHttpModule认识

IHttpHandler

自定义一般处理程序类及配置:

这里只是简单讲讲"可以这么做",对于原理性底层的东西,博客园有详细资料,这里略过.(IIs处理机制,文件处理映射等)

对于一般的情况下,.Net本身已经提供了.ashx处理程序,就是实现IHttpHandler接口,只要在PR方法写我们自己的逻辑代码即可;

本质也是IIS收到后缀名为.ashx文件,交给isapi.dll映射给相应的处理程序进行处理,这样我们也可以自定义程序来处理自定义后缀名文件;

    /// <summary>
    /// 根据业务返回数据
    /// </summary>
    public class MyHttpHandler:IHttpHandler
    {
        public bool IsReusable
        {
            get { return true; }
        }

        public void ProcessRequest(HttpContext context)
        {
            context.Response.Write("处理自定义后缀名程序文件");
        }
    }

假设自定义一个后缀为.YZR的文件,使用MyHttpHandler来处理,需要在webconfig文件进行配置一下:
<system.webServer>
    <handlers>
      <add name="myhandler" path="*.YZR" verb="GET,POST" type="UI.MyHttpHandler"/>
    </handlers>

</system.webServer>

path指后缀名,verb指提交方式,type指处理程序类的全名称;

Note:

lIIS集成模式下配置
l <system.webServer>
l<!--适配IIS集成模式-->
l    <handlers>
l      <add name="iishander" path="*.do" verb="*" type="WebApplication1.IISHandler1"/>
l    </handlers>
l  </system.webServer>
lIIS经典模式下配置
l<system.web>
l <httpHandlers>
l      <add path="*.do" verb=“GET,POST" type="WebApplication1.IISHandler1" />
l    </httpHandlers>
l  </system.web>
lVerb:注意一定要写成大写的GET,POST
IHttpHandler可以做验证码,通过Ajax方式的交互等
 
IHttpModule

提供给程序员自定义功能后,注册到事件管道上运行;

在Asp.Net或者Asp.net MVC中一个http的请求相应都会跑管道事件,IHttpModule就是在这个地方进行一些过滤处理的,当然.Net Framework已经对管道事件进行了处理(从BeginRequest开始,对用户信息权限进行检验,在第7个管道完成了缓存的处理,8管道.ashxPR方法,9-10Session的处理,11,12处理aspx页面等我们写的代码,13,14开始释放请求,15,16完成处理完的缓存,17,18日志,19渲染);我们自己也可以在这个基础进行添加自己的代码:

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

        public void Init(HttpApplication context)
        {
            context.BeginRequest += context_BeginRequest;
        }

        void context_BeginRequest(object sender, EventArgs e)
        {
            HttpContext.Current.Response.Write("已经经过我手处理完了");
        }
    }

 <modules>
      <add name="mymodule" type="UI.MyHttpModule"/>
    </modules>
  </system.webServer>

这里每当http请求过来,都会走自定义的MyHttpModule.

实际开发的话,都是在最开始就截取http请求,即在BeginRequest,这样在全局文件中注册管道事件即可,并不需要自己自定义:

一般的话,IHttpModule可以做url的重写(伪静态),图片的防盗链(或者图片的水印处理)等等

Url的重写:

protected void Application_BeginRequest(object sender, EventArgs e)
        {
            string oldUrl = Context.Request.RawUrl;
            string newUrl = string.Empty;
            System.Text.RegularExpressions.Regex reg = new System.Text.RegularExpressions.Regex("/Index/(.*)/(.*)");
            if(reg.IsMatch(oldUrl))
            {
                newUrl = reg.Replace(oldUrl, "/Index.aspx?id=$1&username=$2");
                Context.RewritePath(newUrl);
            }

        }

具体的写法可以根据逻辑进行改造;

原文地址:https://www.cnblogs.com/Francis-YZR/p/4770919.html