ASP.NET MVC Http Module and Http Handler


  1. 說明
    1. Http Module
    2. Http Handler
  2. 參考資料

筆記 ASP.NET MVC Request Lifecycle 中 Http Moudle 與 Http Handler 的所扮演的角色。

logo

說明

Http Module

Http Module 可以對 Requests 提供服務,同時一個 Requests 可以受到多個 Http Module 的作用

Http Module 可以參與 Request 並進行修改與提供服務

必須由向應用程式進行註冊(Register)

被設計用於參與 Lifecycle 中的任何相關事件

藉由實作 IHttpMoudle Interface

public class CustomMoudle : IHttpModule
{
    private HttpApplication context;

    public void Dispose()
    {
        throw new NotImplementedException();
    }

    public void Init(HttpApplication context)
    {
        throw new NotImplementedException();
    }
}

Http Handler

對於 Request 而言,只有單一的 Http Handler 可以接受此 Request 並進行處理

Handler 負責產生 Response 進行回應

必須由向應用程式進行註冊(Register)

設計用於對應特定事件

藉由實作 IHttpHandler Interface

public class CustomHandler : IHttpHandler
{
    public bool IsReusable
    {
        get { return false; }
    }

    public void ProcessRequest(HttpContext context)
    {
        context.Response.Write("<h1>Custom Handler</h1>");
    }
}

RouteConfig.cs

public class RouteConfig
{
    public static void RegisterRoutes(RouteCollection routes)
    {
        routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

        routes.Add(new Route("home/lab", new CustomRouteHandler()));

        routes.MapRoute(
            ...
        );
    }
}
public class CustomRouteHandler : IRouteHandler
{
    public IHttpHandler GetHttpHandler(RequestContext requestContext)
    {
        return new CustomHandler();
    }
}

參考資料

pluralsight - The MVC Request Life Cycle