Home > Blockchain >  How to enable xml pretty print in .NET Core 5
How to enable xml pretty print in .NET Core 5

Time:10-11

I wanted that raw response from backend when calling like this:

GET http://localhost:49610/docs/3085
Accept: application/xml
Authorization: Bearer {{jwtToken}}

would be:

<SolutionReportResponseDto xmlns:i="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://schemas.datacontract.org/2004/07/Company.Common.NetStandard.Dtos">
  <Metadata />
  <Databases />
  <Variables />
</SolutionReportResponseDto>

instead of:

<SolutionReportResponseDto xmlns:i="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://schemas.datacontract.org/2004/07/Company.Common.NetStandard.Dtos"><Metadata /><Databases /><Labels /><Variables /></SolutionReportResponseDto>

I managed to do this with next code:

services.AddControllers().AddXmlDataContractSerializerFormatters();

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

  xmlWriterSettings.Indent = true;
});

Is there a shorter way? So I can set Indent in AddXmlDataContractSerializerFormatters() method? Not sure how to use MvcXmlOptions either?

public static IMvcBuilder AddXmlDataContractSerializerFormatters(this IMvcBuilder builder, Action<MvcXmlOptions> setupAction);

CodePudding user response:

I ended up with this:

services.AddControllers(options =>
{
  // Works around IE 11's caching behavior for API calls
  options.Filters.Add(new ResponseCacheAttribute { NoStore = true, Location = ResponseCacheLocation.None });
                
  options.OutputFormatters.RemoveType<XmlDataContractSerializerOutputFormatter>();
  options.OutputFormatters.Add(new XmlDataContractSerializerOutputFormatter(new XmlWriterSettings() { Indent = true }));
});

CodePudding user response:

You can also simply add this in .NET Core 6

builder.Services.AddMvc(options =>
{
    options.OutputFormatters.Add(new XmlSerializerOutputFormatter());
});

You will need to reference namespace 'using Microsoft.AspNetCore.Mvc.Formatters;'

in .NET 5

services.AddMvc(options =>
{
    options.OutputFormatters.Add(new XmlSerializerOutputFormatter());
});

CodePudding user response:

The MvcOptionsis different as the MvcXmlOptions, you should use AddControllersWithViews method to set it instead of using the AddXmlDataContractSerializerFormatters.

More details, you could refer to below codes:

         services.AddControllersWithViews( options => {
            {
                XmlWriterSettings xmlWriterSettings = options.OutputFormatters
                  .OfType<XmlDataContractSerializerOutputFormatter>()
                  .Single()
                  .WriterSettings;

                xmlWriterSettings.Indent = true;
            }
        }).AddXmlDataContractSerializerFormatters() ;
  • Related