# 模块二 基础巩固 HTTP管道与中间件

## 2.3.2 Web API -- HTTP管道与中间件 <a href="#id-232webapihttp-guan-dao-yu-zhong-jian-jian" id="id-232webapihttp-guan-dao-yu-zhong-jian-jian"></a>

* 管道
* 中间件

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

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

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

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

### 管道 <a href="#guan-dao" id="guan-dao"></a>

![](https://3083743005-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F8gwpNo3eyzHkX0O40HRA%2Fuploads%2F9HtA2EZsa1gZPMfyQqWO%2F187.jpg?alt=media\&token=9a06126c-b475-43dd-8d68-47073dbc0b8e)

### 中间件 <a href="#zhong-jian-jian" id="zhong-jian-jian"></a>

![](https://3083743005-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F8gwpNo3eyzHkX0O40HRA%2Fuploads%2FQZ2rnq0C4HtRVbRkCPZy%2F188.jpg?alt=media\&token=79400f29-9bfa-4295-b4c3-553c3f3c0c08)

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();
    });
}
```

#### 自定义的中间件 <a href="#zi-ding-yi-de-zhong-jian-jian" id="zi-ding-yi-de-zhong-jian-jian"></a>

```
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源码链接： <a href="#github-yuan-ma-lian-jie" id="github-yuan-ma-lian-jie"></a>

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