.NET Core開發日誌——Middleware

dapan發表於2021-09-09

熟悉ASP.NET架構的開發者一定對於HTTP Modules與HTTP Handlers不陌生。兩者的作用主要是對網路請求執行特定的處理工作。而在.NET Core中,它們都被Middleware(中件間)取代了。

之前的Http Modules和HTTP Handlers是如下圖般處理請求的:

圖片描述

現在變成了這樣:

圖片描述

一言概括之,Middleware完成了HTTP Modules與HTTP Handlers的原有工作,但又不是簡單的化二為一的減法作用。

Middleware減去的其實是與原來ASP.NET中重要的基礎——應用程式生命週期事件()的繫結。

HTTP Modules在初始化時就需要針對HttpApplication的事件作繫結處理,這樣當HttpApplication的各項事件被觸發時,已繫結的相應處理程式才會按照預期的那樣被執行。

public class HelloWorldModule : IHttpModule{    public HelloWorldModule()    {
    }    public String ModuleName
    {        get { return "HelloWorldModule"; }
    }    // In the Init function, register for HttpApplication 
    // events by adding your handlers.
    public void Init(HttpApplication application)    {
        application.BeginRequest += 
            (new EventHandler(this.Application_BeginRequest));
        application.EndRequest += 
            (new EventHandler(this.Application_EndRequest));
    }    private void Application_BeginRequest(Object source, 
         EventArgs e)    {    // Create HttpApplication and HttpContext objects to access
    // request and response properties.
        HttpApplication application = (HttpApplication)source;
        HttpContext context = application.Context;
        context.Response.Write("

            HelloWorldModule: Beginning of Request             


");     }    private void Application_EndRequest(Object source, EventArgs e)    {         HttpApplication application = (HttpApplication)source;         HttpContext context = application.Context;         context.Response.Write("

            HelloWorldModule: End of Request

");     }    public void Dispose()    {     } }

然後你還需要在web.config配置檔案註冊這個HTTP Module。


    
        
           
        
    

如果是用Middleware的話,事情就變得很簡單了。拋棄IHttpModule介面及HttpModule實現類,不用再關心HttpApplication的任何事件,還有煩人的web.config配置。直接在程式碼中以最簡潔的方式完成工作。

    public void Configure(IApplicationBuilder app, IHostingEnvironment env){
    app.Use(async(context, next) =>{        await context.Response.WriteAsync("Beginning of Requestn");        await next.Invoke();        await context.Response.WriteAsync("End of Requestn");
    });
    app.Run(async (context) =>
    {        await context.Response.WriteAsync("Hello World!n");
    });
}

圖片描述

相似的,對於HTTP Handlers,雖然不用取消對HttpApplication事件的依賴,但以兩者的程式碼實現方式作比較,Middleware亳無疑問勝出一籌。

public class HelloWorldHandler : IHttpHandler{    public HelloWorldHandler()    {
    }    public void ProcessRequest(HttpContext context)    {
        HttpRequest Request = context.Request;
        HttpResponse Response = context.Response;        // This handler is called whenever a file ending 
        // in .sample is requested. A file with that extension
        // does not need to exist.
        Response.Write("");
        Response.Write("");
        Response.Write("

Hello from a synchronous custom HTTP handler.

");         Response.Write("");         Response.Write("");     }    public bool IsReusable     {        // To enable pooling, return true here.         // This keeps the handler in memory.         get { return false; }     } }

仍需要在web.config檔案中註冊HTTP handler。


    
        
            
        
    

換作Middleware的寫法:

private static void HandleSample(IApplicationBuilder app){
    app.Run(async context =>
    {        await context.Response.WriteAsync("Hello Sample");
    });
}// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.public void Configure(IApplicationBuilder app, IHostingEnvironment env){
    app.MapWhen(context => context.Request.Path.Value.EndsWith("sample"), HandleSample);
}

圖片描述

總結下使用Middleware的優點:

  • 沒有對HttpApplication的依賴

  • 沒有對IHttpModule與IHttpHandler介面的依賴

  • 無需在web.config檔案中新增各種配置

  • 程式碼簡潔

最後需要補充Middleware與HTTP Modules的一點差異。各Middleware中處理請求與響應的順序是剛好相反的,越早處理請求的Middleware越晚處理響應。而HTTP Modules中處理請求與響應的順序則保持一致,因為每個HTTP Module請求與響應事件的繫結都是在同一階段完成的。

原文出處

來自 “ ITPUB部落格 ” ,連結:http://blog.itpub.net/758/viewspace-2804134/,如需轉載,請註明出處,否則將追究法律責任。

相關文章