客官請看圖
圖中的Httphandler就是處理程序。
兩者的共同點
如果把aspx處理程序和ashx處理程序放到上圖中,他們是處在相同的位置的,
他們都實現了IHttphandler接口。實現了
IHttphandler才具備處理請求的能力
兩者的不同點
微軟對aspx下足了功夫,做了相當大的包裝,里面含有控件,viewstate,還有自己的生命周期。
為了讓開發人員更好的處理請求,微軟采用了事件機制,讓程序員可以在aspx的生命周期類 注入代碼。
aspx是比ashx復雜的多的處理程序版本。
實現自己的處理程序
讓用戶訪問127.0.0.1/hello.zz的時候,輸出一些信息,把他當處理程序使用。
在一個a目錄下建立app_code文件夾
新建hanler.cs文件,代碼如下:
1 using System; 2 using System.Web; 3 4 public class helloZZ : IHttpHandler { 5 6 public void ProcessRequest (HttpContext context) { 7 context.Response.ContentType = "text/plain"; 8 context.Response.Write("你請求的是hello.zz文件"); 9 } 10 11 public bool IsReusable { 12 get { 13 return false; 14 } 15 } 16 17 }
再在a目錄下建立handler.ashx,代碼如下:
<%@ WebHandler Language="C#" Class="MyHandler" %> using System; using System.Web; public class MyHandler : IHttpHandler { public void ProcessRequest (HttpContext context) { context.Response.ContentType = "text/plain"; context.Response.Write("Hello World"); } public bool IsReusable { get { return false; } } }
再建立如下的web.config
<?xml version="1.0"?> <configuration> <system.web> <compilation debug="false" targetFramework="4.0" /> <httpHandlers> <add path="hello.zz" verb="*" type="helloZZ"/> </httpHandlers> </system.web> </configuration>
特殊說明:
請直接用vs2012打開handler.ashx,右鍵用瀏覽器打開,這樣做的只是為了構建一個web環境。
再請求hello.zz就可以了

