【问题标题】:Default input formatter in ASP.NET Core 2ASP.NET Core 2 中的默认输入格式化程序
【发布时间】:2018-02-18 12:28:03
【问题描述】:
在 ASP.NET Core 2 应用程序中,我有一个带有 [FromBody] 属性的操作。参数由 ASP.NET 引擎从 JSON 主体转换为模型对象。
但仅当请求的Content-Type 设置为application/json 时才有效。如果未设置标头,则返回 415 (Unsupported Media Type) HTTP 错误。
如何将[FromBody]绑定的默认格式化程序设置为JSON,这样即使Content-Type请求头没有设置,它也会绑定模型?
【问题讨论】:
标签:
asp.net-mvc
asp.net-core-mvc
【解决方案1】:
如果您没有指定内容类型,则它假定的默认内容类型是“文本/纯文本”。您可以使用以下代码强制应用程序将有效负载视为 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"));
}
}
);
}