ASP.NET Core系列:中間件

1. 概述

  ASP.NET Core中的中間件是嵌入到應用管道中用於處理請求和響應的一段代碼。app

2. 使用 IApplicationBuilder 建立中間件管道

2.1 匿名函數

  使用Run, Map, Use ,MapWhen等擴展方法來實現。async

using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;

public class Startup
{
    public void Configure(IApplicationBuilder app)
    {
        app.Run(async context =>
        {
            await context.Response.WriteAsync("Hello World!");
        });
    }
}

  第一個Run委託終止了管道。函數

  用 Use 將多個請求委託連接在一塊兒。 next 參數表示管道中的下一個委託。 可經過不 調用 next 參數使管道短路。ui

public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
    app.Use(async (context, next) =>
    {
        context.Response.ContentType = "text/plain;charset=utf-8";

        await context.Response.WriteAsync("進入第一個委託 執行下一個委託以前\r\n");

        // 調用管道中的下一個委託
        await next.Invoke();

        await context.Response.WriteAsync("結束第一個委託 執行下一個委託以後\r\n");
    });

    app.Run(async context =>
    {
        await context.Response.WriteAsync("進入第二個委託\r\n");

        await context.Response.WriteAsync("Hello World!\r\n");

        await context.Response.WriteAsync("結束第二個委託\r\n");
    });
}

2.2 自定義中間件類

  新建中間件類:MyMiddleware.csthis

using Microsoft.AspNetCore.Http;

public class MyMiddleware
{
    private readonly RequestDelegate _next;

    // 在應用程序的生命週期中,中間件的構造函數只會被調用一次
    public MyMiddleware(RequestDelegate next)
    {
        this._next = next;
    }

    public async Task InvokeAsync(HttpContext context)
    {
        await context.Response.WriteAsync("Hello World!");

        await _next(context);
    }
}

  將自定義中間件配置到請求處理管道中,Startup.cs文件調整:spa

public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
    app.UseMiddleware<MyMiddleware>();
}

  將中間件MyMiddleware改爲擴展方法:code

  新建擴展類MyMiddlewareExtension.cs中間件

using Microsoft.AspNetCore.Builder;

public static class MyMiddlewareExtension
{
    public static IApplicationBuilder UseMyMiddleware(this IApplicationBuilder builder)
    {
        // 使用UseMiddleware將自定義中間件添加到請求處理管道中
        return builder.UseMiddleware<MyMiddleware>();
    }
}

  將自定義中間件配置到請求處理管道中,Startup.cs文件調整:blog

public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
    app.UseMyMiddleware();
}

2.3 自定義中間件類傳入初始參數

public class GreetingOption
{
    public string At { get; set; }

    public string To { get; set; }
}
using Microsoft.AspNetCore.Http;

public class GreetingMiddleware
{
    private readonly RequestDelegate _next;
    private readonly GreetingOption _option;

    public GreetingMiddleware(RequestDelegate next, GreetingOption option)
    {
        _next = next;
        _option = option;
    }

    public async Task Invoke(HttpContext context)
    {
        var message = $"Good {_option.At} {_option.To}";
        await context.Response.WriteAsync(message);
    }
}
using Microsoft.AspNetCore.Builder;

public static class GreetingMiddlewareExtension
{
    public static IApplicationBuilder UseGreetingMiddleware(this IApplicationBuilder app, GreetingOption option)
    {
        return app.UseMiddleware<GreetingMiddleware>(option);
    }
}
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
    app.UseGreetingMiddleware(new GreetingOption
    {
        At = "Morning",
        To = "Libing"
    });
}

3. IMiddleware

  IMiddleware提供了強類型約束的中間件,其默認實現是MiddlewareFactory,接口定義以下:接口

public interface IMiddleware
{
    Task InvokeAsync(HttpContext context, RequestDelegate next);
}

  IMiddlewareFactory用於建立IMiddleware實例及對實例進行回收,接口定義:

public interface IMiddlewareFactory
{
    public IMiddleware Create (Type middlewareType);
    
    public void Release (IMiddleware middleware);
}

3.1 自定義IMiddleware類型中間件

  修改MyMiddleware,實現IMiddleware接口:

using Microsoft.AspNetCore.Http;

public class MyMiddleware : IMiddleware
{
    public async Task InvokeAsync(HttpContext context, RequestDelegate next)
    {
        await context.Response.WriteAsync("Hello World!");

        await next(context);
    }
}

  將自定義中間件配置到請求處理管道中,Startup.cs文件調整:

public void ConfigureServices(IServiceCollection services)
{
    // 在服務容器中註冊自定義中間件
    services.AddSingleton<MyMiddleware>();
}

public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
    // 使用 UseMiddleware() 把自定義中間件添加到管道中
    app.UseMyMiddleware();
}
相關文章
相關標籤/搜索