ASP.NET Core中間件與HttpModule有何不同

前言

在ASP.NET Core中最大的更改之一是對Http請求管道的更改,在ASP.NET中我們了解HttpHandlerHttpModule但是到現在這些已經被替換為中間件那麼下面我們來看一下他們的不同處。

HttpHandler

Handlers處理基於擴展的特定請求,HttpHandlers作為進行運行,同時做到對ASP.NET響應請求。他是一個實現System.Web.IHttphandler介面的類。任何實現IHttpHandler介面的類都可以作為Http請求處理響應的目標程式。
它提供了對文件特定的擴展名處理傳入請求,
ASP.NET框架提供了一些默認的Http處理程式,最常見的處理程式是處理.aspx文件。下面提供了一些默認的處理程式。

Handler Extension Description
Page Handler .aspx handle normal WebPages
User Control Handler .ascx handle Web user control pages
Web Service Handler .asmx handle Web service pages
Trace Handler trace.axd handle trace functionality

創建一個自定義HttpHandler


public class CustomHttpHandler:IHttpHandler
{
    
    public bool IsReusable
    {
        //指定是否可以重用處理程式
        get {return true;}
    }
    
    public void ProcessRequest(HttpContext context)
    {
        //TODO
        throw new NotImplementedException();
    }
}

在web.config中添加配置項

<!--IIS6或者IIS7經典模式-->  
  <system.web>  
    <httpHandlers>  
      <add name="mycustomhandler" path="*.aspx" verb="*" type="CustomHttpHandler"/>  
    </httpHandlers>  
  </system.web>  
   
<!--IIS7集成模式-->  
  <system.webServer>  
    <handlers>  
       <add name="mycustomhandler" path="*.aspx" verb="*" type="CustomHttpHandler"/>  
    </handlers>  
  </system.webServer>  

非同步HttpHandlers

非同步的話需要繼承HttpTaskAsyncHandler類,HttpTaskAsyncHandler類實現了IHttpTaskAsyncHandlerIHttpHandler介面

public class CustomHttpHandlerAsync:HttpTaskAsyncHandler
{
    
    public override Task ProcessRequestAsync(HttpContext context)
    {

        throw new NotImplementedException();
    }
}

HttpModule

下面是來自MSDN

Modules are called before and after the handler executes. Modules enable developers to intercept, participate in, or modify each individual request. Modules implement the IHttpModule interface, which is located in the System.Web namespace.

HttpModule類似過濾器,它是一個基於事件的,在應用程式發起到結束的整個生命周期中訪問事件

自定義一個HttpModule

public class CustomModule : IHttpModule
    {
        public void Dispose()
        {
            throw new NotImplementedException();
        }

        public void Init(HttpApplication context)
        {
            context.BeginRequest += new EventHandler(BeginRequest);
            context.EndRequest += new EventHandler(EndRequest);
        }
        void BeginRequest(object sender, EventArgs e)
        {
            ((HttpApplication)sender).Context.Response.Write("請求處理前");
        }

        void EndRequest(object sender, EventArgs e)
        {
            ((HttpApplication)sender).Context.Response.Write("請求處理結束後");
        }
    }


web.config中配置

<!--IIS6或者IIS7經典模式-->  
<system.web>  
    <httpModules>  
      <add name="mycustommodule" type="CustomModule"/>  
    </httpModules>  
  </system.web>  
<!--IIS7集成模式-->  
<system.webServer>  
    <modules>  
      <add name="mycustommodule" type="CustomModule"/>  
    </modules>  
</system.webServer>  

中間件

中間件可以視為集成到Http請求管道中的小型應用程式組件,它是ASP.NET中HttpModule和HttpHandler的結合,它可以處理身份驗證、日誌請求記錄等。

中間件和HttpModule的相似處

中間件和HttpMoudle都是可以處理每個請求,同時可以配置進行返回我們自己的定義。

中間件和httpModule之間的區別

HttpModule 中間件
通過web.config或global.asax配置 在Startup文件中添加中間件
執行順序無法控制,因為模組順序主要是基於應用程式生命周期事件 可以控制執行內容和執行順序按照添加順序執行。
請求和響應執行順序保持不變 響應中間件順序與請求順序相反
HttpModules可以附件特定應用程式事件的程式碼 中間件獨立於這些事件

中間件示例

 public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
  {
      if (env.IsDevelopment())
      {
          app.UseDeveloperExceptionPage();
      }

      app.UseHttpsRedirection();

      app.UseRouting();

      app.UseAuthorization();

      app.UseEndpoints(endpoints =>
      {
          endpoints.MapControllers();
      });
  }

在如上程式碼片段中我們有一些中間件的添加,同時也有中間件的順序。

Reference

//www.talkingdotnet.com/asp-net-core-middleware-is-different-from-httpmodule/

//support.microsoft.com/en-us/help/307985/info-asp-net-http-modules-and-http-handlers-overview