【问题标题】:Disable JSON Support in ASP.NET MVC Web API在 ASP.NET MVC Web API 中禁用 JSON 支持
【发布时间】:2021-04-15 23:32:21
【问题描述】:

在创建新的基于 MVC Web API 的服务时,我们希望首先关注 XML,然后使用具有原生 JSON.NET 支持的完整版本添加 JSON 功能作为增强功能。为此,我们希望阻止服务以 JSON 格式接受请求或提供响应,以避免建立我们预期会破坏的任何功能。

有没有办法在 ASP.NET MVC API 中禁用 JSON 支持?

【问题讨论】:

    标签: asp.net-mvc-4 asp.net-web-api


    【解决方案1】:

    您所要做的就是删除 JSON 媒体格式化程序。

    // Identify JSON formatters in global config.
    var jsonMediaTypeFormatters = GlobalConfiguration.Configuration.Formatters
        .Where(x => x.SupportedMediaTypes
        .Any(y => y.MediaType.Equals("application/json", StringComparison.InvariantCultureIgnoreCase)))
        .ToList();
    
    // Remove formatters from global config.
    foreach (var formatter in jsonMediaTypeFormatters)
    {
        GlobalConfiguration.Configuration.Formatters.Remove(formatter);
    }
    

    【讨论】:

    • 这就是我所期望的解决方案。很高兴看到一些关于如何做到这一点的代码。
    • @ProgrammingHero 你去吧。已更新。
    • 在哪里可以找到 GlobalConfiguration 对象?
    【解决方案2】:

    还有一个更短的选项,因为只能有一个 Json 格式化程序,并且 MediaTypeFormatterCollection 将其作为属性公开。从 Web API 2 开始可用(可能也在 v1 中,不确定)。

    GlobalConfiguration.Configuration.Formatters.Remove(controllerSettings.Formatters.JsonFormatter)

    【讨论】:

    • 这段代码在哪里?我的 Startup 类中没有 Formatters 属性
    猜你喜欢
    • 2012-06-20
    • 1970-01-01
    • 1970-01-01
    • 2012-08-10
    • 2013-06-24
    • 1970-01-01
    • 1970-01-01
    • 2012-07-27
    • 2020-02-16
    相关资源
    最近更新 更多