How to configure the default XmlSerializer used in .net core api

Viewed 2005

Does anybody know how to configure the XML serializer which is added when you use the IMVCBuilder in the Startup up class of a .net core api project. Specifically when you use this:

services.AddMvc()
    .AddJsonOptions(options =>
    {
        options.SerializerSettings.DateFormatHandling = Newtonsoft.Json.DateFormatHandling.IsoDateFormat; // UTC (ISO 8601) format for dates
        options.SerializerSettings.NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore;
    })
    .AddXmlSerializerFormatters()
    .AddXmlDataContractSerializerFormatters()

I tried using the AddXmlOptions extension method but there are no properties the MvcXmlOptions Class (apart from AllowRfc7807CompliantProblemDetailsFormat)

The specific setting I am trying to configure is to omit the xml declaration from the root element. There a plenty of answers on here which address this but they all involve instantiating a new XmlSerializer. I need the setting to apply the default serializer used by a controller when the Accept header is set to application/xml

2 Answers

You can get to the XmlWriterSettings used by the output-formatter using something like the following:

services.Configure<MvcOptions>(options =>
{
    var xmlWriterSettings = options.OutputFormatters
        .OfType<XmlSerializerOutputFormatter>()
        .Single()
        .WriterSettings;

    xmlWriterSettings.OmitXmlDeclaration = true;
});

The call to AddXmlSerializerFormatters adds an instance of XmlSerializerOutputFormatter. The code above finds that particular instance and modifies its settings accordingly.

Try this:

services.Configure<MvcXmlOptions>(options =>
{
    //set options here
});
Related