How to force ASP.NET Web API to always return JSON?
ASP.NET Web API默认情况下执行内容协商-将返回基于
清除所有格式化程序,然后重新添加JSON格式化程序。
| 1 2 | GlobalConfiguration.Configuration.Formatters.Clear(); GlobalConfiguration.Configuration.Formatters.Add(new JsonMediaTypeFormatter()); | 
编辑
我把它加到了
仅支持ASP.NET Web API中的JSON–正确的方法
用jsonContentNegotiator替换IContentNegotiator:
| 1 2 3 | var jsonFormatter = new JsonMediaTypeFormatter(); //optional: set serializer settings here config.Services.Replace(typeof(IContentNegotiator), new JsonContentNegotiator(jsonFormatter)); | 
JSonContentNegotiator实现:
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | 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")); } } | 
Philip W给出了正确的答案,但为了清晰和完整的工作解决方案,请编辑global.asax.cs文件,如下所示:(注意,我必须将引用system.net.http.formatting添加到stock生成的文件中)
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 | 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()); } } } | 
| 1 | GlobalConfiguration.Configuration.Formatters.XmlFormatter.SupportedMediaTypes.Clear(); | 
这将清除XML格式化程序,因此默认为JSON格式。
受Dmitry Pavlov出色答案的启发,我稍微修改了它,以便可以插入我想要执行的任何格式化程序。
归功于德米特里。
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 | /// <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)); } } | 
如果您只想对一个方法执行此操作,那么将您的方法声明为返回
| 1 2 3 4 |     public HttpResponseMessage GetAllWhatever() { return Request.CreateResponse(HttpStatusCode.OK, new List<Whatever>(), Configuration.Formatters.JsonFormatter); } | 
此代码对于单元测试来说很麻烦,但也可能是这样:
| 1 2 3 |     sut = new WhateverController() { Configuration = new HttpConfiguration() }; sut.Configuration.Formatters.Add(new Mock<JsonMediaTypeFormatter>().Object); sut.Request = new HttpRequestMessage(); | 
这设置了正确的标题。看起来有点优雅。
| 1 2 3 4 | public JsonResult<string> TestMethod()  { return Json("your string or object"); } | 
对于那些使用OWIN的人
| 1 2 | GlobalConfiguration.Configuration.Formatters.Clear(); GlobalConfiguration.Configuration.Formatters.Add(new JsonMediaTypeFormatter()); | 
变为(在startup.cs中):
| 1 2 3 4 5 6 7 8 9 10 |    public void Configuration(IAppBuilder app) { OwinConfiguration = new HttpConfiguration(); ConfigureOAuth(app); OwinConfiguration.Formatters.Clear(); OwinConfiguration.Formatters.Add(new DynamicJsonMediaTypeFormatter()); [...] } | 
您可以在webapiconfig.cs中使用:
| 1 | config.Formatters.JsonFormatter.SupportedMediaTypes.Add(new MediaTypeHeaderValue("text/html")); |