Go to my github

.NET 云原生架构师训练营(模块二 基础巩固 HTTP管道与中间件)--学习笔记

2.3.2 Web API -- HTTP管道与中间件

  • 管道
  • 中间件

ASP.NET Core 中间件:https://docs.microsoft.com/zh-cn/aspnet/core/fundamentals/middleware/?view=aspnetcore-5.0

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

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

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

管道

中间件

Startup.cs

// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
    if (env.IsDevelopment())
    {
        app.UseDeveloperExceptionPage();
    }

    // 默认启用 https
    app.UseHttpsRedirection();
    app.UseRouting();
    app.UseCors();
    app.UseAuthentication();
    app.UseAuthorization();

    app.UseEndpoints(endpoints =>
    {
        endpoints.MapControllers();
    });
}

自定义的中间件

app.Run(async context =>
{
    await context.Response.WriteAsync("my middleware");
});

启动程序,输出如下:

my middleware

使用 app.Run 之后管道中止,不会继续执行 app.UseEndpoints,如果想要继续执行,可以使用 app.Use 并调用 next()

app.Use(async (context, next) =>
{
    await context.Response.WriteAsync("my middleware 1");
    await next();
});

app.Run(async context =>
{
    await context.Response.WriteAsync("my middleware 2");
});

启动程序,输出如下:

my middleware 1my middleware 2

GitHub源码链接:

https://github.com/MingsonZheng/ArchitectTrainingCamp/tree/main/HelloApi

知识共享许可协议

课程链接

https://appsqsyiqlk5791.h5.xiaoeknow.com/v1/course/video/v_5f39bdb8e4b01187873136cf?type=2

本作品采用知识共享署名-非商业性使用-相同方式共享 4.0 国际许可协议进行许可。

欢迎转载、使用、重新发布,但务必保留文章署名 郑子铭 (包含链接: http://www.cnblogs.com/MingsonZheng/ ),不得用于商业目的,基于本文修改后的作品务必以相同的许可发布。

如有任何疑问,请与我联系 (MingsonZheng@outlook.com) 。

posted @ 2020-12-21 23:11  郑子铭  阅读(191)  评论(0编辑  收藏  举报