从中间件设置 ASP.NET Core 中 HttpResponse 的原因

问题描述:

如何在来自某些中间件的 ASP.NET Core 中的 HTTP 响应上设置原因短语?

How can I set the reason phrase on a HTTP response in ASP.NET Core from some middleware?

在以前的版本(完整框架)中,我会执行以下操作:

In previous versions (full framework), I would do the following:

context.Response.StatusCode = 401;
context.Response.ReasonPhrase = "Missing or invalid token.";

在 ASP.NET Core 中,唯一可用的属性是 StatusCode.

In ASP.NET Core, the only property available is the StatusCode.

这是一个 Fiddler 捕获示例,在响应中设置了自定义原因.

Here is an example of a Fiddler capture with a custom reason set on the response.

试试这个:

context.Response.StatusCode = 401;
context.Response.HttpContext.Features.Get<IHttpResponseFeature>().ReasonPhrase = "Missing or invalid token.";