MVC 6更改返回内容类型 [英] MVC 6 change return content-type
问题描述
我似乎无法在新的Asp.net MVC 6中更改控制器方法的返回内容类型.
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");
在过去的WebApi时代,我可以使用它,并更改格式器:
In the old WebApi days I could use this, and change the formatter:
return Request.CreateResponse(HttpStatusCode.OK, data, JsonMediaTypeFormatter.DefaultMediaType);
我可以在MVC 6中做类似的事情吗?
Could I do something similar in MVC 6?
推荐答案
您可以通过在控制器操作上设置Produces("ResultType")
属性来实现.例如:
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 };
}
给定结果类型的formatter
将用于转换object
,而与Accept Header
无关.
The formatter
for the given result type will be used to convert the object
, regardless of the Accept Header
.
但是您需要为响应类型注册一个formatter
.因此,如果要使用"text/x-vcard"
,则必须为此创建一个格式化程序.
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.
为此,您需要创建一个实现IOutputFormatter
的类,并在Startup.cs
中的ConfigureServices()
方法中将其注册,如下所示:
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:
这篇关于MVC 6更改返回内容类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!