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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With