MVC 6 change return content type

It seems I cannot change the return type of the content of my controller method in the new Asp.net MVC 6.

I tried various options:

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

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

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

Can I do something like this in MVC 6?

+5
source share
1 answer

You can do this by setting the Produces("ResultType") attribute to the controller action. For instance:

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

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

But for the type of response, you must register the formatter . Therefore, if you want to use "text/x-vcard" , you will need to create a formatter for it.

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

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

Here are some additional resources that can help you:

Content Consolidation in MVC 6

Formatting in ASP.NET MVC 6

+9
source

Source: https://habr.com/ru/post/1232936/


All Articles