.Net Core MiddleWare

发布时间 2023-08-03 19:11:04作者: qfccc

作用

中间件是一种装配到应用管道以处理请求和响应的软件。 每个组件:

  • 选择是否将请求传递到管道中的下一个组件。
  • 可在管道中的下一个组件前后执行工作。

请求委托用于生成请求管道。 请求委托处理每个 HTTP 请求。

Use

执行顺序为: 自定义中间件1Request -> 自定义中间件2Request -> ...Request -> 自定义中间件2Response -> 自定义中间件1Response

第一种

app.Use(async (conext, next) =>
{
    await conext.Response.WriteAsync("<h1>(1)</h1>");
    await next(conext);
    await conext.Response.WriteAsync("<h1>(1)</h1>");
});

第二种

使用拓展方法实现,在program.cs 文件中可以使用 app.MiddlewareExtexns() 达到相同的效果

namespace ExceptiopnWebApp.Expansion
{
    public static class MiddlewareExtexns
    {
        public static IApplicationBuilder UseMiddleWare(this IApplicationBuilder app)
        {
            return app.Use(async (conext, next) =>
            {
                await conext.Response.WriteAsync("<h1>(2)</h1>");
                await next(conext);
                await conext.Response.WriteAsync("<h1>(2)</h1>");
            });
        }
    }
}

UseMiddleWare

  1. 需要提供: public async Task InvokeAsync(HttpContext context)
  2. 如果中间件需要继续向下执行需要提供 private readonly RequestDelegate _next;

CustomMiddleWare.cs

namespace ExceptiopnWebApp.Middleware
{
    public class CustomMiddleWare
    {
        private readonly RequestDelegate _next;
        public CustomMiddleWare(RequestDelegate next)
        {
            _next = next;
        }

        public async Task InvokeAsync(HttpContext context)
        {
            await context.Response.WriteAsync("UseMiddleWare1");
            await _next(context);
            await context.Response.WriteAsync("UseMiddleWare1");
        }
    }
}

Program.cs

app.UseMiddleware<CustomMiddleWare>();

Map

  • 浏览器地址上出现字符匹配就进入你的中间件
app.Map("/Hello", app =>
{
    app.Use(async (context, next) =>
    {
        await context.Response.WriteAsync("World");
        await next(context);
    });
});

MapWhen

  • 条件成功就进入你的中间件
app.MapWhen(conext =>
{
    return conext.Request.Path.Value?.Contains("Name") ?? false;
}, app =>
{
    app.Use(async (context, next) =>
    {
        await context.Response.WriteAsync("Job!!!");
        await next(context);
    });
});