您需要創建一個自定義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