简体   繁体   English

更改响应内容类型

[英]Changing Response content-type

Using C#, .NET Core 3.1.使用 C#、.NET 核心 3.1。

I am trying to set the response content-type header value for particular controllers (not all controllers in the project).我正在尝试为特定控制器(不是项目中的所有控制器)设置响应内容类型 header 值。 At the moment, I have this but I am not sure if I am doing it right.目前,我有这个,但我不确定我是否做得对。 Am I in the right direction with this code I have?我拥有的这段代码是否朝着正确的方向发展?

public class MyCustomFilter: ActionFilterAttribute
{
    public override void OnActionExecuted(HttpActionExecutedContext actionExecutedContext)
    {
       actionExecutedContext.Response.Headers.Add("testAddingHeader", "123456");
       //Can I do change Content-Type here too?
    }
}

In my controller class:在我的 controller class 中:

[MyCustomFilter()] // Do I need to use [ServiceFilter(typeof(MyActionFilterAttribute))]?
public class SampleController : Controller
{
    public IActionResult Index()
    {
        return Ok("Hello World.");
    }

UPDATE I followed the better suggestion from Silkfire.更新我遵循了 Silkfire 的更好建议。

This worked for me but I get a 406 from the browser.这对我有用,但我从浏览器得到 406。 Does it mean the content was delivered to the browser but is unwilling to render it as it was not part of the accepted content type (specified in request)?这是否意味着内容已交付给浏览器但不愿意呈现它,因为它不是接受的内容类型(在请求中指定)的一部分? Key thing is that the response made it to the client.关键是响应已发送给客户端。 Thanks!谢谢!

    [Produces("application/somethingcustom")]

I inspected the response to the browser via Fiddler.我通过 Fiddler 检查了对浏览器的响应。 Seems that the raw body content is empty - does that meant the server is doing some changes to the response body and not just simply changing the response content-type header?似乎原始正文内容为空 - 这是否意味着服务器正在对响应正文进行一些更改,而不仅仅是更改响应内容类型 header?

UPDATE 2 Found the reason why: Looks like I need to write my own custom formatter as I noticed this when accessing the controller action:更新 2找到原因:看起来我需要编写自己的自定义格式化程序,因为我在访问 controller 操作时注意到了这一点:

No output formatter was found for content types to write the response.

You should be able to set the global content-type on a controller using the Produces attribute.您应该能够使用Produces属性在 controller 上设置全局内容类型。

[Produces("application/json")]
public class SampleController : Controller

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM