问题描述:
No media types found in 'Microsoft.AspNet.OData.Formatter.ODataInputFormatter.SupportedMediaTypes'. Add at least one media type to the list of supported media types.
我的项目.netcore3.1中集成了OData框架,大部分接口支持了Odata协议,但有少部分接口不需要实现odata协议。我创建了普通webapi接口,如果我的接口参数传入这个时候swagger就不能生成文档,直接报上面的错误。根据错误大概意思就是匹配不到media types我的理解就是没得content-type类型。
有了大概思路找解决方案就简单了,在services.AddControllers中设置SupportedMediaTypes,参考代码如下:
services.AddControllers(options =>
{
var outputFormatList = options.OutputFormatters.OfType<ODataInputFormatter>().Where(_ => _.SupportedMediaTypes.Count == 0);
foreach (var outputFormatter in outputFormatList)
{
outputFormatter.SupportedMediaTypes.Add(new MediaTypeHeaderValue("application/json"));
}
var inputFormatList = options.InputFormatters.OfType<ODataInputFormatter>().Where(_ => _.SupportedMediaTypes.Count == 0);
foreach (var inputFormatter in inputFormatList)
{
inputFormatter.SupportedMediaTypes.Add(new MediaTypeHeaderValue("application/json"));
}
});
这里有个坑是services.AddControllers必须放到services.AddOData()后面,不然还是会报错。
到这里启动运行正常。