Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible in ASP.NET Core to enable XmlSerialization for a single controller

I have a Web API that has several controllers, one of which returns XML for legacy reasons, while all the others return JSON.

In a .NET Framework I can selectively enable XML serialization for a single controller by accessing HttpControllerSettings.Formatters (typically in an attribute used to decorate the controller).

Is it possible to do the same in ASP.NET Core, i.e. only enable Xml serialization for a single controller?

The only way I've found to enable Xml serialization in ASP.NET Core 2.1 is globally, using:

services.AddMvc()
     .SetCompatibilityVersion(CompatibilityVersion.Version_2_1)
     .AddXmlSerializerFormatters();

This works OK, but has a side-effect that I consider to be undesirable: when I run the application in Visual Studio I see a trace of an warning from XmlSerializerOutputFormatter something like:

Microsoft.AspNetCore.Mvc.Formatters.XmlSerializerOutputFormatter:Warning: An error occurred while trying to create an XmlSerializer for the type 'MyApp.MyModel'.

System.InvalidOperationException: There was an error reflecting type 'MyApp.MyModel'. ---> System.InvalidOperationException: Cannot serialize member ... see inner exception for more details. ---> System.NotSupportedException: Cannot serialize ... because it is an interface.
   --- End of inner exception stack trace ---
   at System.Xml.Serialization.StructModel.CheckSupportedMember(TypeDesc typeDesc, MemberInfo member, Type type)
   ...
   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)

It appears to be trying to create an XmlSerializer for a Type that is not used by my "XML" controller.

While it's not a showstopper, I'd prefer not to be creating XmlSerializers except when I need them.

like image 311
Joe Avatar asked Nov 01 '25 07:11

Joe


2 Answers

I've encountered the same issue. I do not believe there is a solution at the moment, so I've created a feature request on the Github project.

In the meantime, I've set

"Logging": { 
    "LogLevel": {
        "Microsoft.AspNetCore.Mvc.Formatters.XmlSerializerOutputFormatter":  "Error"
    }
}

To suppress the warnings during startup.

like image 56
Alexander Stathis Avatar answered Nov 04 '25 03:11

Alexander Stathis


I've encountered the same issue.Then I changed my code:

builder.Services.AddControllers().AddNewtonsoftJson().AddXmlSerializerFormatters();

U can check this one out, I hope it's has been helpful.

like image 43
Grezz Su Avatar answered Nov 04 '25 01:11

Grezz Su