MVC 6 change return content-type

╄→гoц情女王★ 提交于 2019-12-21 13:26:15

问题


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?


回答1:


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



来源:https://stackoverflow.com/questions/32942608/mvc-6-change-return-content-type

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!