[ASP.NET Core] Middleware


前言

本篇文章介紹ASP.NET Core里,用來處理HTTP封包的Middleware,為自己留個紀錄也希望能幫助到有需要的開發人員。

結構

  • 在ASP.NET Core里,每個從「瀏覽器傳入」的HTTP Request封包,會被系統封裝為「HttpRequest對象」,並且配置默認的HttpResponse對象、Session對象、ClaimsPrincipal對象...等等物件。接着將這些對象,封裝成為一個「HttpContext對象」,用來提供ASP.NET Core后續使用。

    結構01

  • ASP.NET Core在收到HttpContext之后,會把它交給一個「Pipeline」去處理。這個Pipeline里面配置很多「Middleware」。系統會將HttpContext,依序傳遞給Pipeline里的Middleware去處理。每個Middleware會依照自己內部的程序邏輯,來運算處理HttpContext,並且變更HttpContext所封裝的對象內容。

    結構02

  • ASP.NET Core在收到經由Middleware處理完畢的HttpContext之后,就會取出其中所封裝的HttpResponse對象。然后依照這個HttpResponse對象,來建立從「服務器回傳」的HTTP Response封包內容。

    結構03

  • ASP.NET Core經由上述的系統結構,完成HTTP Request封包輸入、HTTP Response封包輸出的工作流程。

    結構04

開發

Invoke

[ASP.NET Core] Getting Started這篇文章里,提供了一個ASP.NET Core的Middleware范例:HelloWorldMiddleware。在這個范例里,Middleware透過實做Invoke方法,來提供自己所封裝的程序邏輯。

public class HelloWorldMiddleware
{
    // Fields
    private readonly RequestDelegate _next;

    // Constructors
    public HelloWorldMiddleware(RequestDelegate next)
    {
        _next = next;
    }

    // Methods
    public Task Invoke(HttpContext context)
    {
        // Response
        context.Response.WriteAsync("Hello World!");

        // Return
        return Task.CompletedTask;
    }
}

開發01

HttpContext.Request

在實做Middleware.Invoke方法的時候,開發人員可以透過HttpContext.Request,來取得從「瀏覽器傳入」的HTTP Request封包內容。在下列的范例程序代碼里,就是透過HttpContext.Request的Path、QueryString兩個屬性,來分別取得HTTP Request封包的URL路徑與QueryString內容。

public class HelloWorldMiddleware
{
    // Fields
    private readonly RequestDelegate _next;

    // Constructors
    public HelloWorldMiddleware(RequestDelegate next)
    {
        _next = next;
    }

    // Methods
    public Task Invoke(HttpContext context)
    {
        // Request
        string path = context.Request.Path.ToString();
        string queryString = context.Request.QueryString.ToString();
        string message = string.Format("path={0}, queryString={1}", path, queryString);

        // Response
        context.Response.WriteAsync(message);

        // Return
        return Task.CompletedTask;
    }
}

開發02

HttpContext.Response

同樣在實做Middleware.Invoke方法的時候,開發人員可以透過HttpContext.Response,來設定從「服務器回傳」的HTTP Response封包內容。在下列的范例程序代碼里,就是透過HttpContext.Response的WriteAsync方法、StatusCode屬性,來分別設定HTTP Response封包的Content與StatusCode。

public class HelloWorldMiddleware
{
    // Fields
    private readonly RequestDelegate _next;

    // Constructors
    public HelloWorldMiddleware(RequestDelegate next)
    {
        _next = next;
    }

    // Methods
    public Task Invoke(HttpContext context)
    {
        // Response
        context.Response.StatusCode = 404;
        context.Response.WriteAsync("Not Found");

        // Return
        return Task.CompletedTask;
    }
}

開發03

Exception

而在實做Middleware.Invoke方法的時候,如果程序代碼里發生了預期之外的Exception。ASP.NET Core預設會使用「500 Internal Server Error」,這個StatusCode來通報系統內部發生異常。 在下列的范例程序代碼里,就是直接拋出一個例外錯誤,交由ASP.NET Core的錯誤處理機制去處理。

public class HelloWorldMiddleware
{
    // Fields
    private readonly RequestDelegate _next;

    // Constructors
    public HelloWorldMiddleware(RequestDelegate next)
    {
        _next = next;
    }

    // Methods
    public Task Invoke(HttpContext context)
    {
        // Exception
        throw new Exception();

        // Return
        return Task.CompletedTask;
    }
}

開發04

RequestDelegate

建立Middleware的時候,開發人員可以透過建構子所傳入的RequestDelegate,來參考到Pipeline里的下一個Middleware。透過調用RequestDelegate,就可以調用Pipeline里的下一個Middleware的Invoke方法。在下列的范例程序代碼里,就是透過調用RequestDelegate,來調用Pipeline里的下一個Middleware的Invoke方法,藉此串接其他Middleware的程序邏輯。

public class HelloWorldMiddleware
{
    // Fields
    private readonly RequestDelegate _next;

    // Constructors
    public HelloWorldMiddleware(RequestDelegate next)
    {
        _next = next;
    }

    // Methods
    public async Task Invoke(HttpContext context)
    {
        // Do Something 01
        //....

        // Next
        await _next.Invoke(context);

        // Do Something 02
        // ...
    }
}

參考


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM