Home > Back-end >  .NET 6 web api project needs to export XML and JSON
.NET 6 web api project needs to export XML and JSON

Time:05-21

I have a web api project that has some actions (most) that need to export JSON, and some (only a few) that need to export as XML.

Since XML isn't supported by default, i've added the

services.AddControllers(options =>
{
    options.OutputFormatters.Add(new Microsoft.AspNetCore.Mvc.Formatters.XmlSerializerOutputFormatter());
})

bit to my Startup.cs, and added to the Action that needs XML:

[Produces("application/xml")]
public async Task<IActionResult> ExportAsKML(Guid id)

And this works for that method, but now ALL of my controller actions default to XML. How can I keep the default to JSON, but only use XML for a certain few actions?

CodePudding user response:

Have you changed the order of your formats in OutputFormatters?

Accroding to the offcial document :Formatters are evaluated in the order they're inserted, where the first one takes precedence. : enter image description here when I debug: enter image description here the default format become xml with out other settings,

in this order, enter image description here

enter image description here

  • Related