如何向 ASP.NET Core Web API 响应添加自定义标头 [英] How to add custom header to ASP.NET Core Web API response
问题描述
我正在将我的 API 从 Web API 2 移植到 ASP.NET Core Web API.我曾经能够通过以下方式添加自定义标题:
I am porting my API from Web API 2 to ASP.NET Core Web API. I used to be able to add a custom header in the following manner:
HttpResponseMessage response = new HttpResponseMessage(HttpStatusCode.OK);
response.Headers.Add("X-Total-Count", count.ToString());
return ResponseMessage(response);
如何在 ASP.NET Core Web API 中添加自定义标头?
How does one add a custom header in ASP.NET Core Web API?
推荐答案
您可以从传入的 Http Request
中劫持 HttpContext
并添加您自己的自定义标头在调用返回之前到 Response
对象.
You can just hi-jack the HttpContext
from the incoming Http Request
and add your own custom headers to the Response
object before calling return.
如果您希望自定义标头持久存在并添加到跨多个控制器的所有 API 请求中,那么您应该考虑制作一个为您执行此操作的 Middleware
组件,然后将其添加到 Http 请求中Startup.cs
If you want your custom header to persist and be added in all API requests across multiple controllers, you should then consider making a Middleware
component that does this for you and then add it in the Http Request Pipeline in Startup.cs
public IActionResult SendResponse()
{
Response.Headers.Add("X-Total-Count", "20");
return Ok();
}
这篇关于如何向 ASP.NET Core Web API 响应添加自定义标头的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!