关于.NET Core中间件的四种请求方式!

C# · 2023-10-01 · 13024 人浏览
关于.NET Core中间件的四种请求方式!

1、中间件概述(类似拦截器)

中间件流程图

  • 用于组成应用程序管道来处理请求和响应的组件。
  • 请求委托用于生成请求管道,处理每个HTTP请求。
  • 每个中间件组件:

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

    • 每个委托在下一个委托之前和之后都有机会执行操作。
    • 任何委托都能选择停止传递到下一个委托。
  • 默认中间件:

    • 错误处理
    • 静态文件服务器
    • 身份验证
    • MVC

2、配置HTTP请求管道

四种方法:Run()、Use()、Map()、MapWhen()

2.1、Run()

  • Run()方法会短路通道,因为它不会调用next请求委托。(所以Run()方法一般都是放在最后)

    app.run(async context => await context.response.writeasync("hello 1!");
     子);
    app.run(async context => await context.response.writeasync("hello 2!");
     子);

2.2、Use()

  • 上述Run()方法等同于不使用next的Use()方法:

    app.use(async (context, next) => await
    context.response.writeasync("hello 1!");
    ;);
    app.run(async context => await context.response.writeasync("hello 2!");
    ;);

2.3、Map()

  • 用于匹配基于请求路径的请求委托。

    • 只接受路径,并配置单独的中间件管道的功能。
      -

    如下案例,任何基于路径/api的请求都会被管道中所配置的HandleMapApi()方法处理:

    public void cofffigure(iapplicationbuilder ap r app)
    {
     app.map("/api",handlemapapi);
    }
    
    private void HandleMapApi(iapplicationbuilder app)
    {
     app.Run(async context => { await context.Response.Writeasunc("Map Api successfull!");
     });
    }

2.4、MapWhen()

● 支持基于谓词的中间件分支,允许以非常灵活的方式构建单独的管道。(当什么条件....)

  • 谓语类型:Func<HttpContext,bool>
  • 如下案例:
public void configure(iapplicationbuilder app)
{
    app.MapWhen(
        context => context.request.query.containskey("uid"),
        HandleMapDetail
    );
    app.Run(async context => await context.Response.WriteAsync("hello guest!");
    });
}
private void HandleMapDetail(iapplicationbuilder app)
{
    app.Run(asunc context =>{
        await context.Response.WriteAsync("Hello User!");
    });
}
C# .NET Core 中间件