Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MVC 6 change return content-type

I seem to be unable to change the return content-type of my controller-method in the new Asp.net MVC 6.

I tried various variations on:

Context.Response.Headers.Add("Content-type", "text/x-vcard");

In the old WebApi days I could use this, and change the formatter:

return Request.CreateResponse(HttpStatusCode.OK, data, JsonMediaTypeFormatter.DefaultMediaType);

Could I do something similar in MVC 6?

like image 425
mhtsbt Avatar asked Oct 05 '15 06:10

mhtsbt


1 Answers

You can do that by setting the Produces("ResultType") attribute on the controller action. For example:

[Produces("application/xml")]
public Object Index()
{
    return new { Id = 100 };
}

The formatter for the given result type will be used to convert the object, regardless of the Accept Header.

But you need to have a formatter registered for the response type. So if you want to use "text/x-vcard", you'd have to create a formatter for that.

To do that you need to create a class that implements IOutputFormatter and register it in Startup.cs in the ConfigureServices() method like this:

services.Configure<MvcOptions>(options =>
{
    options.OutputFormatters.Add(new VCardFormatter());
});

Here are some additional resources that may help you do that:

Content negotiation in MVC 6

Formatters in ASP.NET MVC 6

like image 79
Domysee Avatar answered Nov 15 '22 00:11

Domysee