您需要创建一个自定义System.Net.Http.Formatting.IContentNegotiator类,并将所选格式器检入Negotiate
方法中。
public class ApplicationContentNegotiator : IContentNegotiator
{
private readonly JsonMediaTypeFormatter _jsonFormatter;
private readonly MediaTypeHeaderValue _jsonMediaType;
private readonly XmlMediaTypeFormatter _xmlFormatter;
private readonly MediaTypeHeaderValue _xmlMediaType;
public static IContentNegotiator Create()
{
return new ApplicationContentNegotiator();
}
private ApplicationContentNegotiator()
{
_jsonFormatter = new JsonMediaTypeFormatter();
_jsonMediaType = MediaTypeHeaderValue.Parse("application/json");
_xmlFormatter = new XmlMediaTypeFormatter();
_xmlMediaType = MediaTypeHeaderValue.Parse("application/xml");
}
public ContentNegotiationResult Negotiate(Type type, HttpRequestMessage request, IEnumerable<MediaTypeFormatter> formatters)
{
var controller = new DefaultHttpControllerSelector(request.GetConfiguration()).SelectController(request);
if (controller.ControllerName == "MyController")
return new ContentNegotiationResult(_xmlFormatter, _xmlMediaType);
return new ContentNegotiationResult(_jsonFormatter, _jsonMediaType);
}
}
然后更换您IContentNegotiator
实施服务为HttpConfiguration
对象
GlobalConfiguration.Configuration.Services.Replace(typeof(IContentNegotiator), ApplicationContentNegotiator.Create());
谢谢阿尔贝托,很好的解决方案。但我们决定使用另一种方法。 – 2015-02-10 11:28:06
@IvanKononenko有什么办法? :) – RyanY 2016-02-17 03:59:14