Web Api 返回JSON的多种方式

In Global.asax add the line

Application_Start() class:

GlobalConfiguration.Configuration.Formatters.XmlFormatter.SupportedMediaTypes.Clear();

In the WebApiConfig.cs, add to the end of the Register function

// Remove the XML formatter
config.Formatters.Remove(config.Formatters.XmlFormatter);

IContentNegotiator

 public class JsonContentNegotiator : IContentNegotiator
    {
        private readonly JsonMediaTypeFormatter _jsonFormatter;

        public JsonContentNegotiator(JsonMediaTypeFormatter formatter)
        {
            _jsonFormatter = formatter;
        }

        public ContentNegotiationResult Negotiate(Type type, HttpRequestMessage request, IEnumerable<MediaTypeFormatter> formatters)
        {
            var result = new ContentNegotiationResult(_jsonFormatter, new MediaTypeHeaderValue("application/json"));
            return result;
        }
    }

In WebApiConfig.cs :

   // resutn json
   var jsonFormatter = new JsonMediaTypeFormatter();
   config.Services.Replace(typeof(IContentNegotiator), new JsonContentNegotiator(jsonFormatter));

Thanks

posted @ 2016-07-11 13:24  游子善心  阅读(3)  评论(0编辑  收藏  举报  来源