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?
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With