更改响应内容类型

时间:2021-06-11 08:06:22

标签: c# asp.net-core asp.net-core-webapi

使用 C#、.NET Core 3.1。

我正在尝试为特定控制器(并非项目中的所有控制器)设置响应内容类型标头值。目前,我有这个,但我不确定我是否做得对。使用此代码,我的方向是否正确?

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

在我的控制器类中:

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

更新 我遵循了 Silkfire 的更好建议。

这对我有用,但我从浏览器收到了 406。这是否意味着内容已交付给浏览器但由于它不是接受的内容类型(在请求中指定)的一部分而不愿意呈现它?关键是响应已发送到客户端。谢谢!

    [Produces("application/somethingcustom")]

我通过 Fiddler 检查了对浏览器的响应。原始正文内容似乎是空的 - 这是否意味着服务器正在对响应正文进行一些更改,而不仅仅是更改响应内容类型标头?

更新 2 找到原因了! 看起来我需要编写自己的自定义格式化程序,因为我在访问控制器操作时注意到了这一点:

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

1 个答案:

答案 0 :(得分:1)

您应该能够使用 Produces 属性在控制器上设置全局内容类型。

[Produces("application/json")]
public class SampleController : Controller
相关问题