ASP.NET Core中介軟體與HttpModule有何不同

HueiFeng發表於2020-06-08

前言

在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

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

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

相關文章