ASP.NET Core 2 中的默认输入格式化程序

ale*_*xey 4 asp.net-mvc asp.net-core-mvc

在 ASP.NET Core 2 应用程序中,我有一个带有[FromBody]属性的操作。ASP.NET 引擎将参数从 JSON 主体转换为模型对象。

但只有当Content-Type请求设置为时它才有效application/json。如果未设置标头,则返回415(不支持的媒体类型) HTTP 错误。

如何将绑定的默认格式化程序设置为 JSON [FromBody],以便即使Content-Type未设置请求标头也会绑定模型?

Tha*_*rai 5

如果您未指定内容类型,则其假定的默认内容类型为“text/plain”。您可以使用以下代码强制应用程序将有效负载视为 json 内容,

public void ConfigureServices(IServiceCollection services)
        {
            services.AddMvc(config =>
            {
                foreach (var formatter in config.InputFormatters)
                {
                    if (formatter.GetType() == typeof(JsonInputFormatter))
                        ((JsonInputFormatter)formatter).SupportedMediaTypes.Add(
                            Microsoft.Net.Http.Headers.MediaTypeHeaderValue.Parse("text/plain"));
                }
            }
            );
        }
Run Code Online (Sandbox Code Playgroud)