我正在.NETCore(2.2.0)中创建一个需要同时支持XML和JSON的API。对于绝大多数端点,默认情况下它必须以XML响应,但是如果客户端请求,则应遵循“ Accept”标头以返回JSON。工作正常。
一个控制器是一种特殊情况,因为它仅需要支持JSON,并且具有作为字典的响应。对此控制器的请求会产生正确的JSON响应,但是在我的日志中,我看到一个System.NotSupportedException,该异常源自“ Microsoft.AspNetCore.Mvc.Formatters.XmlSerializerOutputFormatter.CreateSerializer”
如果删除操纵OutputFormatters列表顺序的代码,则看不到异常。
在startup.cs中,我的ConfigureServices方法包含以下内容:
services.AddMvc()
.AddXmlSerializerFormatters();
services.Configure<MvcOptions>(options =>
{
var outputFormatters = options.OutputFormatters;
var jsonOutputFormatter = outputFormatters.First(f => f is JsonOutputFormatter);
// Remove JSON output formatter and reappend at end to default to XML
outputFormatters.Remove(jsonOutputFormatter);
outputFormatters.Add(jsonOutputFormatter);
// Allow the client to request other content types (JSON)
options.RespectBrowserAcceptHeader = true;
});
可以使用以下控制器再现该错误。
[Route("api/[controller]")]
[Produces("application/json")]
[ApiController]
public class ExampleController : ControllerBase
{
[HttpGet]
public IActionResult GetDict()
{
return Ok(new Dictionary<int, string>());
}
}
调用GET / api / Example时会产生以下警告/错误,并且在'Accept'标头为'application / json'或未提供时都会发生。
Microsoft.AspNetCore.Mvc.Formatters.XmlSerializerOutputFormatter:Warning: An error occurred while trying to create an XmlSerializer for the type 'System.Collections.Generic.Dictionary`2[[System.Int32, System.Private.CoreLib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e],[System.String, System.Private.CoreLib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e]]'.
System.NotSupportedException: The type System.Collections.Generic.Dictionary`2[[System.Int32, System.Private.CoreLib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e],[System.String, System.Private.CoreLib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e]] is not supported because it implements IDictionary.
at System.Xml.Serialization.TypeScope.GetDefaultIndexer(Type type, String memberInfo)
at System.Xml.Serialization.TypeScope.ImportTypeDesc(Type type, MemberInfo memberInfo, Boolean directReference)
at System.Xml.Serialization.TypeScope.GetTypeDesc(Type type, MemberInfo source, Boolean directReference, Boolean throwOnError)
at System.Xml.Serialization.ModelScope.GetTypeModel(Type type, Boolean directReference)
at System.Xml.Serialization.XmlReflectionImporter.ImportTypeMapping(Type type, XmlRootAttribute root, String defaultNamespace)
at System.Xml.Serialization.XmlSerializer..ctor(Type type, String defaultNamespace)
at System.Xml.Serialization.XmlSerializer..ctor(Type type)
at Microsoft.AspNetCore.Mvc.Formatters.XmlSerializerOutputFormatter.CreateSerializer(Type type)
有没有一种方法可以防止此警告,但默认情况下仍保持所有其他以XML响应的控制器的预期行为?