XmlSerializerInputFormatter is obsolete - ASP.NET Core 2.1

风流意气都作罢 提交于 2019-12-01 16:42:06

问题


I am using the following to accept XML serialized in my Core API App.

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

After updating to ASP.NET Core 2.1 I receive the following warning:

'XmlSerializerInputFormatter.XmlSerializerInputFormatter()' is obsolete: 'This constructor is obsolete and will be removed in a future version.'

What is the new way to handle this?


回答1:


According to the source code, there's a constructor that has not been marked as Obsolete:

public XmlSerializerInputFormatter(MvcOptions options)

This constructor takes an instance of MvcOptions, so you can pass through your existing options argument:

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

As of ASP.NET Core 3.0, this constructor is the only one available. Those that were marked obsolete have now been removed.




回答2:


With .NET Core 2.2 or later XmlSerializerInputFormatter should be marked as deprecated.

Instead a of explicitly defining XML serializers as we did before, in the .NET Core 2.2 we can add them simply by calling AddXmlSerializerFormatters() method which will do the job now. Read here why it has been deprecated

Here is how you can do it.

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);
}


来源:https://stackoverflow.com/questions/50818508/xmlserializerinputformatter-is-obsolete-asp-net-core-2-1

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!