如何强制ASP.NET Web API始终返回JSON?

ASP.NET Web API默认进行内容协商 – 将根据Accept标头返回XML或JSON或其他types。 我不需要/想要这个,有没有一种方法(如一个属性或东西)告诉Web API总是返回JSON?

在ASP.NET Web API中只支持JSON – 正确的方法

用JsonContentNegotiatorreplaceIContentNegotiator:

 var jsonFormatter = new JsonMediaTypeFormatter(); //optional: set serializer settings here config.Services.Replace(typeof(IContentNegotiator), new JsonContentNegotiator(jsonFormatter)); 

JsonContentNegotiator实现:

 public class JsonContentNegotiator : IContentNegotiator { private readonly JsonMediaTypeFormatter _jsonFormatter; public JsonContentNegotiator(JsonMediaTypeFormatter formatter) { _jsonFormatter = formatter; } public ContentNegotiationResult Negotiate( Type type, HttpRequestMessage request, IEnumerable<MediaTypeFormatter> formatters) { return new ContentNegotiationResult( _jsonFormatter, new MediaTypeHeaderValue("application/json")); } } 

清除所有格式化程序,然后添加Json格式化程序。

 GlobalConfiguration.Configuration.Formatters.Clear(); GlobalConfiguration.Configuration.Formatters.Add(new JsonMediaTypeFormatter()); 

编辑

我将它添加到Application_Start() Global.asax

菲利普W有正确的答案,但为了清晰和一个完整的工作解决scheme,编辑你的Global.asax.cs文件看起来像这样:(注意我必须添加引用System.Net.Http.Formatting股票生成的文件)

 using System; using System.Collections.Generic; using System.Linq; using System.Net.Http.Formatting; using System.Web; using System.Web.Http; using System.Web.Mvc; using System.Web.Optimization; using System.Web.Routing; namespace BoomInteractive.TrainerCentral.Server { // Note: For instructions on enabling IIS6 or IIS7 classic mode, // visit http://go.microsoft.com/?LinkId=9394801 public class WebApiApplication : System.Web.HttpApplication { protected void Application_Start() { AreaRegistration.RegisterAllAreas(); WebApiConfig.Register(GlobalConfiguration.Configuration); FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters); RouteConfig.RegisterRoutes(RouteTable.Routes); BundleConfig.RegisterBundles(BundleTable.Bundles); //Force JSON responses on all requests GlobalConfiguration.Configuration.Formatters.Clear(); GlobalConfiguration.Configuration.Formatters.Add(new JsonMediaTypeFormatter()); } } } 
 GlobalConfiguration.Configuration.Formatters.XmlFormatter.SupportedMediaTypes.Clear(); 

这将清除XML格式化程序,因此默认为JSON格式。

如果你只想为一个方法做到这一点,然后声明你的方法返回HttpResponseMessage而不是IEnumerable<Whatever>并做:

  public HttpResponseMessage GetAllWhatever() { return Request.CreateResponse(HttpStatusCode.OK, new List<Whatever>(), Configuration.Formatters.JsonFormatter); } 

这个代码是unit testing的痛苦,但也可能是这样的:

  sut = new WhateverController() { Configuration = new HttpConfiguration() }; sut.Configuration.Formatters.Add(new Mock<JsonMediaTypeFormatter>().Object); sut.Request = new HttpRequestMessage(); 

受到德米特里·帕夫洛夫(Dmitry Pavlov)出色的回答的启发,我稍微修改了一下,所以我可以插入任何我想实施的格式化程序。

感谢德米特里。

 /// <summary> /// A ContentNegotiator implementation that does not negotiate. Inspired by the film Taken. /// </summary> internal sealed class LiamNeesonContentNegotiator : IContentNegotiator { private readonly MediaTypeFormatter _formatter; private readonly string _mimeTypeId; public LiamNeesonContentNegotiator(MediaTypeFormatter formatter, string mimeTypeId) { if (formatter == null) throw new ArgumentNullException("formatter"); if (String.IsNullOrWhiteSpace(mimeTypeId)) throw new ArgumentException("Mime type identifier string is null or whitespace."); _formatter = formatter; _mimeTypeId = mimeTypeId.Trim(); } public ContentNegotiationResult Negotiate(Type type, HttpRequestMessage request, IEnumerable<MediaTypeFormatter> formatters) { return new ContentNegotiationResult(_formatter, new MediaTypeHeaderValue(_mimeTypeId)); } } 

呦可以在WebApiConfig.cs中使用:

 config.Formatters.JsonFormatter.SupportedMediaTypes.Add(new MediaTypeHeaderValue("text/html")); 

这有正确的标题设置。 似乎有点优雅。

 public JsonResult<string> TestMethod() { return Json("your string or object"); }