一般处理程序(ashx)和页面处理程序(aspx)的区别

 

客官请看图
 
图中的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就可以了

自定义自己的处理程序.7z
posted @ 2014-02-16 12:30  艾斯泽  阅读(7013)  评论(0编辑  收藏  举报