WebAPI MVC 4设置默认响应类型 [英] WebAPI mvc 4 set default response type
问题描述
我有以下代码
GlobalConfiguration.Configuration.Formatters.XmlFormatter.SupportedMediaTypes.Clear();
config.Formatters.JsonFormatter.MediaTypeMappings.Add(
new UriPathExtensionMapping("json", "application/json"));
config.Formatters.XmlFormatter.MediaTypeMappings.Add(
new UriPathExtensionMapping("xml", "application/xml"));
现在,我想如果某个人不提供像http://apuUrl/getBooks
这样的api扩展名,则它应该默认返回JSON值.
Now I want if some one does not provide extension in api like http://apuUrl/getBooks
it should return by default JSON value.
我的以下情况运行良好:
My following scenarios are working fine:
http://apuUrl/getBooks.json
->返回JSON
http://apuUrl/getBooks.xml
->返回XML
注意:我不想为每个API进行额外的路由
Note: I don't want to make extra routing for every API
推荐答案
How about using a DelegatingHandler to override the acceptheader?
public class MediaTypeDelegatingHandler : DelegatingHandler
{
protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
{
var url = request.RequestUri.ToString();
//TODO: Maybe a more elegant check?
if (url.EndsWith(".json"))
{
// clear the accept and replace it to use JSON.
request.Headers.Accept.Clear();
request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
}
else if (url.EndsWith(".xml"))
{
request.Headers.Accept.Clear();
request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/xml"));
}
return await base.SendAsync(request, cancellationToken);
}
}
在您的配置中:
GlobalConfiguration.Configuration.MessageHandlers.Add(new MediaTypeDelegatingHandler());
还有您的控制器:
public class FooController : ApiController
{
public string Get()
{
return "test";
}
}
如果您转到http://yoursite.com/api/Foo/?.json
,则应返回:
And if you go to http://yoursite.com/api/Foo/?.json
should return:
"test"
http://yoursite.com/api/Foo/?.xml
应该返回
<string xmlns="http://schemas.microsoft.com/2003/10/Serialization/">test</string>
请注意,由于控制器不需要.json-parameter,因此您仍然需要处理route参数输入.这就是为什么?
可能是必需的.
Note that you still need to handle the route parameter input, since the controller doesn't expect the .json-parameter. That's why the ?
may be necessary.
这篇关于WebAPI MVC 4设置默认响应类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!