更改响应 content-type

Changing Response content-type

使用 C#、.NET Core 3.1。

我正在尝试为特定控制器(不是项目中的所有控制器)设置响应 content-type header 值。目前,我有这个,但我不确定我是否做对了。我的代码方向正确吗?

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

在我的控制器中 class:

[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 检查了对浏览器的响应。原始 body 内容似乎是空的 - 这是否意味着服务器正在对响应 body 进行一些更改,而不仅仅是更改响应 content-type header?

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

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

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

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