【问题标题】:Add supported header type to JsonOutputFormatter将支持的标头类型添加到 JsonOutputFormatter
【发布时间】:2023-03-04 06:01:01
【问题描述】:

我的公司在内部 api 等中使用标准格式进行健康检查响应。我们要么在成功时返回内容类型为 application/status+json 的状态,要么在遇到问题时返回 application/problem+json(this proposed spec 的一部分)。

但是,如果我将内容类型设置为其中任何一个,我的响应就会变成空的 406 响应。

那么,我如何告诉 JsonOutputFormatter 它可以将这些 Json 标头类型添加到它的 SupportedMediaTypes 集合中?

我希望我可以这样做:

services.AddMvc().AddJsonOptions(jsonOptions => {
    jsonOptions.SerializerSettings.SupportedMediaTypes.Add("application/problem+json");
});

但我当然找不到办法。

【问题讨论】:

    标签: json asp.net-core-mvc .net-core content-type


    【解决方案1】:

    好的,这是一种方法。我找到了OutputFormatters 集合,并且能够取出 JsonOutputFormatter。从那里您可以添加支持的媒体类型:

            services.AddMvc(mvcOptions => {
                //TODO: make extension method 
                var jFormatter = mvcOptions.OutputFormatters.FirstOrDefault(f => f.GetType() == typeof(JsonOutputFormatter)) as JsonOutputFormatter;
                jFormatter?.SupportedMediaTypes.Add("application/problem+json");
                jFormatter?.SupportedMediaTypes.Add("application/status+json");
            });
    

    或者,作为扩展方法:

        public static IMvcBuilder AddStatusJsonSupport(this IMvcBuilder builder) {
            builder.AddMvcOptions(options => {
                var jFormatter = options.OutputFormatters.FirstOrDefault(f => f.GetType() == typeof(JsonOutputFormatter)) as JsonOutputFormatter;
                jFormatter?.SupportedMediaTypes.Add("application/problem+json");
                jFormatter?.SupportedMediaTypes.Add("application/status+json");
            });
            return builder;
        }
    

    这样称呼:

    services.AddMvc().AddStatusJsonSupport();
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-09-26
      • 1970-01-01
      • 1970-01-01
      • 2019-08-27
      • 1970-01-01
      • 2021-12-24
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多