Changing Response content-type

Viewed 1367

Using C#, .NET Core 3.1.

I am trying to set the response content-type header value for particular controllers (not all controllers in the project). 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:

[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.

This worked for me but I get a 406 from the browser. 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. 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?

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:

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

1 Answers

You should be able to set the global content-type on a controller using the Produces attribute.

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