MVC 6更改返回内容类型

mht*_*sbt 6 asp.net-core-mvc asp.net-core

我似乎无法在新的Asp.net MVC 6中更改我的controller-method的返回内容类型.

我尝试了各种变化:

Context.Response.Headers.Add("Content-type", "text/x-vcard");
Run Code Online (Sandbox Code Playgroud)

在旧的WebApi时代,我可以使用它,并更改格式化程序:

return Request.CreateResponse(HttpStatusCode.OK, data, JsonMediaTypeFormatter.DefaultMediaType);
Run Code Online (Sandbox Code Playgroud)

我可以在MVC 6中做类似的事情吗?

Dom*_*see 11

您可以通过Produces("ResultType")在控制器操作上设置属性来实现.例如:

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

formatter对给定的结果类型将被用来转换object,不管Accept Header.

但是您需要formatter注册响应类型.因此,如果您想使用"text/x-vcard",则必须为此创建格式化程序.

要做到这一点,你需要创建一个实现IOutputFormatterStartup.csConfigureServices()方法中注册它的类,如下所示:

services.Configure<MvcOptions>(options =>
{
    options.OutputFormatters.Add(new VCardFormatter());
});
Run Code Online (Sandbox Code Playgroud)

以下是一些可以帮助您完成此操作的其他资源:

MVC 6中的内容协商

ASP.NET MVC 6中的格式化程序