Set the default WebAPI formatter

We are using WebAPI to mimic the handling of a legacy system, as a result we would like the default response formatter to the XmlFormatter and not the JsonFormatter. The reason is that some of the existing calls to the service do not supply the Accept: HTTP header field.

I can achieve this by removing the JsonFormatter from the Formatters collection and then re-adding it, forcing it to be at the end of the chain.

This then result in the default format response using the XmlFormatter. Although it works, it just doesn't feel correct and although I am moving Json to the back of the collection, there is no guarantee that the XmlFormatter is at the front of the collection.

Ideas/thoughts?

Thanks


Just add formatters in the right order. If ASP.NET Web API finds two formatters for the same content type, it will pick the first one so it is very important to add formatters in the right order.

//somewhere in Web Api config
config.Formatters.Clear();
config.Formatters.Add(new XmlMediaTypeFormatter());
config.Formatters.Add(new JsonMediaTypeFormatter());

So default will be XML, the first formatter, but the API still supports JSON if the request aks for it (with appropriate HTTP header).

Finally, another different approach, is to use a custom IContentNegociator. It will allow you to select the most appropriate MediaTypeFormatter for a given request.

//somewhere in Web Api config
config.Services.Replace(typeof(IContentNegotiator), new MyCustomContentNegotiator());

An example is available here.


当内容类型为json时,这将返回为自动序列化并返回json

 var json = config.Formatters.JsonFormatter;
 json.SerializerSettings.PreserveReferencesHandling = Newtonsoft.Json.PreserveReferencesHandling.Objects;
        config.Formatters.Remove(config.Formatters.XmlFormatter);
((DefaultContractResolver)config.Formatters.JsonFormatter.SerializerSettings.ContractResolver).IgnoreSerializableAttribute = true;
链接地址: http://www.djcxy.com/p/3454.html

上一篇: 禁用Chrome缓存以进行网站开发

下一篇: 设置默认的WebAPI格式化程序