XmlSerializerInputFormatter已过时 - ASP.NET Core 2.1

ahe*_*ick 6 c# xml-serialization asp.net-core asp.net-core-2.1

我使用以下内容接受我的Core API App中的序列化XML.

services.AddMvc(options =>
{
    // allow xml format for input
    options.InputFormatters.Add(new XmlSerializerInputFormatter());
}).SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
Run Code Online (Sandbox Code Playgroud)

更新到ASP.NET Core 2.1后,我收到以下警告:

'XmlSerializerInputFormatter.XmlSerializerInputFormatter()'已废弃:'此构造函数已过时,将在以后的版本中删除.

处理这个问题的新方法是什么?

Kir*_*kin 12

通过看源代码,存在已构造没有被标记为Obsolete:

public XmlSerializerInputFormatter(MvcOptions options)
Run Code Online (Sandbox Code Playgroud)

当这个构造函数接受一个实例时MvcOptions,您应该能够传递现有的options参数,如下所示:

services.AddMvc(options =>
{
    // allow xml format for input
    options.InputFormatters.Add(new XmlSerializerInputFormatter(options));
}) ...
Run Code Online (Sandbox Code Playgroud)

  • 没问题。我刚刚检查了 2.0 源代码,我提到的构造函数是 ASP.NET Core 2.1 中的新构造函数。这是此更改的拉取请求链接到的 [Github 问题](https://github.com/aspnet/Mvc/issues/6858)。 (2认同)

小智 5

对于 .NET Core 2.2 或更高版本,XmlSerializerInputFormatter 应标记为已弃用。

在 .NET Core 2.2 中,我们可以简单地通过调用 AddXmlSerializerFormatters() 方法来添加它们,而不是像我们之前那样显式定义 XML 序列化器,该方法现在可以完成这项工作。在这里阅读为什么它已被弃用

这是您如何做到的。

public void ConfigureServices(IServiceCollection services)
{
    services.AddMvc(config =>
    {
        config.RespectBrowserAcceptHeader = true;
        config.ReturnHttpNotAcceptable = true;

        config.OutputFormatters.Add(new CsvOutputFormatter());
    }).AddXmlSerializerFormatters().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
}
Run Code Online (Sandbox Code Playgroud)