首页 文章

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

提问于
浏览
97

ASP.NET Web API默认执行内容协商 - 将返回基于 Accept 标头的XML或JSON或其他类型 . 我不需要/想要这个,有没有办法(比如属性或东西)告诉Web API总是返回JSON?

9 回答

  • 3

    Supporting only JSON in ASP.NET Web API – THE RIGHT WAY

    用JsonContentNegotiator替换IContentNegotiator:

    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"));
        }
    }
    
  • 10

    清除所有格式化程序并添加Json格式化程序 .

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

    EDIT

    我把它添加到 Global.asax 里面 Application_Start() .

  • 1

    Philip W有正确的答案,但为了清晰和完整的工作解决方案,编辑你的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());
            }
        }
    }
    
  • 157
    GlobalConfiguration.Configuration.Formatters.XmlFormatter.SupportedMediaTypes.Clear();
    

    这将清除XML格式化程序,从而默认为JSON格式 .

  • 0

    受到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));
        }
    }
    
  • 2

    如果您只想为一个方法执行此操作,则将您的方法声明为返回 HttpResponseMessage 而不是 IEnumerable<Whatever> 并执行:

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

    这段代码很难进行单元测试,但这也是可能的:

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

    这有正确的标头集 . 看起来更优雅一点 .

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

    Yo可以在WebApiConfig.cs中使用:

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

    对于那些使用OWIN的人

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

    变成(在Startup.cs中):

    public void Configuration(IAppBuilder app)
            {
                OwinConfiguration = new HttpConfiguration();
                ConfigureOAuth(app);
    
                OwinConfiguration.Formatters.Clear();
                OwinConfiguration.Formatters.Add(new DynamicJsonMediaTypeFormatter());
    
                [...]
            }
    

相关问题