IHttpHandler接口

IHttpHandler接口:定义Asp.net为了使用自定义Http处理程序同步处理Http Web请求而实现的协定。

说明:一旦定义的自己的HttpHandler,对系统的HttpHandler将是覆盖关系。

命名空间:System.Web

程序集:System.Web

语法:public interface IHttpHandler

IHttpHandler成员 :

IsReusable [ri'juzəb!]    获取一个值,该值指示其他请求是否可以使用IHttpHandler实例。

ProcessRequest    通过实现IHttpHandler接口的自定义HttpHandler启用Http Web请求的处理。

IHttpHandler.IsReusable属性

获取一个值,该值指示其他请求是否可以使用IHttpHandler实例。

语法:

bool IsResuable{get;}

IHttpHandler.ProcessRequest方法:

通过实现IHttpHandler接口的自定义HttpHandler启用Http Web请求的处理。

语法:

void ProcessRequest(HttpContext context)

参数:

Context,HttpContext对象,它提供对用于Http请求提供服务的内部服务器对象(如Request、Response、Session和Server)的引用。

 示例:

// Name this C# file HandlerTest.cs and compile it with the
// command line: csc /t:library /r:System.Web.dll HandlerTest.cs.
// Copy HandlerTest.dll to your \bin directory.

using System.Web;
namespace HandlerExample
{
   public class MyHttpHandler : IHttpHandler
   {
      // Override the ProcessRequest method.
      public void ProcessRequest(HttpContext context)
      {
         context.Response.Write("<H1>This is an HttpHandler Test.</H1>");      
         context.Response.Write("<p>Your Browser:</p>");
         context.Response.Write("Type: " + context.Request.Browser.Type + "<br>");
         context.Response.Write("Version: " + context.Request.Browser.Version);
      }

      // Override the IsReusable property.
      public bool IsReusable
      {
         get { return true; }
      }
   }
}

/*
To use this handler, include the following lines in a Web.config file.
<configuration>
   <system.web>
      <httpHandlers>
         <add verb="*" path="handler.aspx" type="HandlerExample.MyHttpHandler,HandlerTest"/>
      </httpHandlers>
   </system.web>
</configuration>
*/

 备注:在一个HttpHandler容器中如果需要访问Session,必须实现IRequiresSessionState接口,这只是一个标记接口,没有任何方法。

Http处理程序与Asp.net页面:

1.我们应当利用Http处理程序资源来实现应用程序特有的功能,它们需要比常规的Web页面被更快的处理。

2.自定义的处理程序不必对用户代码引发任何中间事件(如:Init Load) ,不必托管任何视图状态,而且也不支持任何回发机制。相对于.aspx资源来说,其中只发生呈现步骤。

3.Asp.net页面只是一个Http处理程序,是一个非常复杂而且高级的Http处理程序。底层的处理机制完全相同。

IHttpHandler如何处理Http请求

 当一个Http请求经HttpModule容器传递到HttpHandler容器时,Asp.net Framework会调用HttpHandler的ProcessRequest成员方法来对这个Http请求进行真正的处理。以一个Aspx页面为例,正是在这里一个aspx页面才被系统处理解析,并将处理完成的结果继续经由HttpModule传递下去,直至到达客户端。

对于ASPX页面,ASP.NET Framework在默认情况下是交给System.Web.UI.PageHandlerFactory这个HttpHandlerFactory来处理的。所谓一个HttpHandlerFactory,所谓一个HttpHandlerFactory,是指当一个HTTP请求到达这个HttpHandler Factory时,HttpHandlerFactory会提供出一个HttpHandler容器,交由这个HttpHandler容器来处理这个HTTP请求。 

参考:

http://msdn.microsoft.com/zh-cn/library/7ezc17x8%28v=VS.80%29.aspx 
原文地址:https://www.cnblogs.com/AngelLee2009/p/2218967.html