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

编程入门 行业动态 更新时间:2024-10-19 14:29:34
本文介绍了如何将自定义标头添加到ASP.NET Core Web API响应的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我正在将我的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对象,然后再调用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(); }

更多推荐

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

本文发布于:2023-11-15 02:50:22,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1590484.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:自定义   如何将   ASP   NET   Web

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!