asp.net-mvc 如何强制 ASP.NET Web API 始终返回 JSON?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12629144/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-08 02:17:15  来源:igfitidea点击:

How to force ASP.NET Web API to always return JSON?

asp.net-mvcasp.net-web-api

提问by Borek Bernard

ASP.NET Web API does content negotiation by default - will return XML or JSON or other type based on the Acceptheader. I don't need / want this, is there a way (like an attribute or something) to tell Web API to always return JSON?

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

采纳答案by Dmitry Pavlov

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

在 ASP.NET Web API 中仅支持 JSON——正确的方式

Replace IContentNegotiator with JsonContentNegotiator:

用 JsonContentNegotiator 替换 IContentNegotiator:

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

JsonContentNegotiator implementation:

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

回答by Filip W

Clear all formatters and add Json formatter back.

清除所有格式化程序并重新添加 Json 格式化程序。

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

EDIT

编辑

I added it to Global.asaxinside Application_Start().

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

回答by JJ_Coder4Hire

Philip W had the right answer but for clarity and a complete working solution, edit your Global.asax.cs file to look like this: (Notice I had to add the reference System.Net.Http.Formatting to the stock generated file)

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());
        }
    }
}

回答by Bat_Programmer

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

This clears the XML formatter and thus defaulting to JSON format.

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

回答by Luke Puplett

Inspired by Dmitry Pavlov's excellent answer, I altered it slightly so I could plug-in whatever formatter I wanted to enforce.

受到 Dmitry Pavlov 出色答案的启发,我对其进行了轻微更改,以便我可以插入我想要强制执行的任何格式化程序。

Credit to Dmitry.

归功于德米特里。

/// <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));
    }
}

回答by durilka

If you want to do that for one method only, then declare your method as returning HttpResponseMessageinstead of IEnumerable<Whatever>and do:

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

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

this code is pain for unit testing but that's also possible like this:

这段代码对于单元测试来说很痛苦,但这也是可能的:

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

回答by Netferret

This has correct headers set. Seems a bit more elegant.

这有正确的标题设置。看起来更优雅一些。

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

回答by Carlo Saccone

for those using OWIN

对于那些使用 OWIN 的人

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

becomes (in Startup.cs):

变成(在 Startup.cs 中):

   public void Configuration(IAppBuilder app)
        {
            OwinConfiguration = new HttpConfiguration();
            ConfigureOAuth(app);

            OwinConfiguration.Formatters.Clear();
            OwinConfiguration.Formatters.Add(new DynamicJsonMediaTypeFormatter());

            [...]
        }

回答by Antonio

Yo can use in WebApiConfig.cs:

你可以在 WebApiConfig.cs 中使用:

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