ASP.NET底層機制 (下) HttpHandler

來源:互聯網
上載者:User

1.IHttpHandler介面
    定義了實現一個HttpRequest的處理所必須實現的一些系統約定方法。

    public interface IHttpHandler
    {
        //其他Request是否可以使用IHttpHandler
        bool IsReusable { get; }

        //處理HttpRequest
        void ProcessRequest(HttpContext context);
    }

NET為ASP.NET提供了很多系統預設HttpHandler類,用來適應不同類型的HttpRequest
    比如aspx,在machine.config中是這樣定義的:    
        <add verb="*" path="*.aspx" type="System.Web.UI.PageHandlerFactory"/>
            說明遇到aspx的Request,ASP.Net會將其交給System.Web.UI.PageHandlerFactory的HttpHandler類來處理
如果自己定義了新的HttpHandler,而且在Web.config中指定,則系統只會使用這個新的HttpHandler,而不再使用原先指定的

2.HttpHandler實現了IHttpHandler介面
    一個aspx頁面在HttpHandler容器中的ProcessRequest方法才被系統真正的處理解析——即交給PageHandlerFactory處理,該工廠負責提供一個HttpHandler容器,由其處理HttpRequest

3.如果要在HttpHandler容器中使用Session,必須要實現IRequiresSessionState介面——這隻是一個空介面,一個標記

using System;
using System.Web;
using System.Web.SessionState;

namespace MyNamespace
{
    public class MyHandler:IHttpHandler,IRequiresSessionState
    {
        public MyHandler() {}

        public bool IsReusable
        {
            get
            {
                return true;
            }
        }

        public void ProcessRequest(HttpContext context)
        {
            HttpResponse response = context.Response;
            HttpRequest request = context.Request;

            HttpSessionState Session = context.Session;
            Session["test"] = "hi";

            response.Write("<b>Hello world!</b>");
            response.Write(Session["test"]);
        }
    }
}

同時,還要在Web.config中加上聲明:   <httpHandlers>
        <add verb="*" path="*" type="MyNamespace.MyHandler,MyNamespace"></add>
   </httpHandlers>

4.IHttpHandlerFactory
    待續。。。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.