Asp.Net页面模型---自定义处理程序

来源:互联网 发布:数据泄密安全 编辑:程序博客网 时间:2024/05/21 17:30

asp.net的默认后辍名为aspx,当我们输入*.aspx的时候, Asp.Net页面模型会实例化某个继承自Page的类,完成从URL到HTML文本的转化,那如果想实现自己的后辍名,如sample,在asp.net要如何实现?以下是实现的流程:

环境:

操作系统:WIN2003
IDE: VS2005

基本理论知识,参考一篇文章《ASP.NET WEB页面生命历程》

一 新建WEB站点
VS2005里新建一个WEB项目,命名为HttpHandler,这个不多讲了

二  配置IIS
1)网站属性 -> 主目录 -> 配置-> 在应用程序扩展里点“添加”
2)扩展名输入.sample, 可执行文件参考.aspx,去掉最底下的“确认文件是否存在”选中按钮。
这是为了让IIS在碰到这种后辍时,知道用哪个程序去处理。

三 新建类库项目
项目名为Sample,这个DLL的作用就是处理*.sample资源。
1) HttpHandleFactory.cs

using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;

/// <summary>
/// HttpHandleFactory 的摘要说?
/// </summary>
public class HttpHandleFactory : IHttpHandlerFactory
{
 public HttpHandleFactory()
 {
 }

    public IHttpHandler GetHandler(HttpContext context,
        string requestType, String url, String pathTranslated)
    {
        IHttpHandler handlerToReturn;
        if ("HelloWorld" == url.Substring(url.LastIndexOf('/') + 1, 10))
            handlerToReturn = new HelloWorldHandler();
        else
            return null;
        return handlerToReturn;
    }
    public void ReleaseHandler(IHttpHandler handler)
    {
    }
    public bool IsReusable
    {
        get
        {
            return false;
        }
    }
}

2)   HelloWorldHandler.cs

using System.Web;
public class HelloWorldHandler : IHttpHandler
{
    public HelloWorldHandler()
    {
    }
    public void ProcessRequest(HttpContext context)
    {
        HttpRequest Request = context.Request;
        HttpResponse Response = context.Response;
        Response.Write("<html>");
        Response.Write("<body>");
        Response.Write("<h1>Hello World!</h1>");
        Response.Write("</body>");
        Response.Write("</html>");
    }
    public bool IsReusable
    {
        get { return false; }
    }
}

将这个DLL放到WEB项目的BIN目录下

四) 配置Web.config

修改Web项目的Web.config文件,因为资源类型和处理程序类型之间的关联要通过web.config来设置。

添加以下节点:
<httpHandlers>
   <add verb="GET,POST" path="*.sample" type="HttpHandleFactory,Sample"/>
  </httpHandlers>
说明:path指定资源类型,type前部分说明要处理这个资源的类,后部分说明这个类所在的namespace

五) 测试

我的测试URL为:http://localhost:2620/Http/HelloWorld.sample,在页面上会输出“Hello World!”。

 

原创粉丝点击