宇宙超能无敌之饼干怪

首页 新随笔 联系 管理

middleware的编写和注册

编写中间件类(middleware-class)

  • 通常,中间件封装在类中,并且通过扩展方法公开。
  • 具有类型为 RequestDelegate 的参数的公共构造函数。
public LoggingMiddleware(RequestDelegate next)
{
    _next = next;
}
  • 名为 InvokeInvokeAsync 的公共方法。 此方法必须:

    • 返回 Task
    • 接受类型 HttpContext 的第一个参数。
  • 构造函数和 Invoke/InvokeAsync 的其他参数由依赖关系注入 (DI) 填充。

public async Task Invoke(HttpContext context)
{
    Console.WriteLine($"Request path: {context.Request.Path}");
    Console.WriteLine($"Request time: {DateTime.Now}");

    await _next(context);
}

LoggingMiddleware.cs

public class LoggingMiddleware  
{
    private readonly RequestDelegate _next;

    public LoggingMiddleware(RequestDelegate next)
    {
        _next = next;
    }


    public async Task Invoke(HttpContext context)
    {
        Console.WriteLine($"Request path: {context.Request.Path}");
        Console.WriteLine($"Request time: {DateTime.Now}");

        await _next(context);
    }
}

注册middleware两种方法

  • 通常,创建扩展方法以通过 IApplicationBuilder 公开中间件:
public static class RequestCultureMiddlewareExtensions
{
    public static IApplicationBuilder UseRequestLog(
        this IApplicationBuilder builder)
    {
        return builder.UseMiddleware<LoggingMiddleware>();
    }
}
// 注册middleware
app.UseRequestLog();
  • 或者使用UseMiddleware函数传入
app.UseMiddleware<LoggingMiddleware>();
posted on 2024-04-27 20:56  lazycookie  阅读(10)  评论(0编辑  收藏  举报