且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何将自定义标头添加到ASP.NET Core Web API响应

更新时间:2023-02-15 13:12:54

您可以从传入的Http Request中劫持HttpContext并将您自己的自定义标头添加到Response对象,然后再调用return.

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 Request Pipeline中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();
}