gpt4 book ai didi

c# - 为什么 ASP.NET Core 只执行一次自定义中间件?

转载 作者:太空狗 更新时间:2023-10-29 20:12:27 25 4
gpt4 key购买 nike

我有一个 ASP.NET Core,带有以下接受 POST 请求的 Controller :

[Route("api/v1/tenants/tests")]
public class TestsController : Controller
{
[HttpPost]
public IActionResult Post(string tenantId)
{
return Ok();
}
}

我开发了一个“空”中间件来测试。它在Startup.cs 文件的Configure 方法中定义:

public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}

app.UseMvc();

app.Use(async (context, next) =>
{
// Forward to the next one.
await next.Invoke();
});
}

问题

当我通过 Postman 调用 Controller 时,对 POST 方法的初始调用成功通过中间件,然后到达 Controller 。但是,以下调用直接转到 Controller ,完全跳过中间件。这是为什么?

最佳答案

中间件必须在调用app.UseMvc()之前设置。

public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}

app.Use(async (context, next) =>
{
// Forward to the next one.
await next.Invoke();
});

// !! Have to be called after setting up middleware !!
app.UseMvc();
}

此信息存在于 documentation 中但我不知道它也适用于自定义中间件:

The order that middleware components are added in the Startup.Configure method defines the order in which the middleware components are invoked on requests and the reverse order for the response. The order is critical for security, performance, and functionality.

The following Startup.Configure method adds middleware components for common app scenarios:

1 - Exception/error handling

2 - HTTP Strict Transport Security Protocol

3 - HTTPS redirection

4 - Static file server

5 - Cookie policy enforcement

6 - Authentication

7 - Session

8 - MVC

更新

在 ASP.Net Core 3.0 中,你需要在 MapControllers() 之前添加你的中间件

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

关于c# - 为什么 ASP.NET Core 只执行一次自定义中间件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52612494/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com