Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Return complete XML response from ASP .NET Core Web API method

I'm approaching ASP.NET Core taking advantage of a customer request about a web service.

The request is a web method that returns data in XML format, like this:

<?xml version="1.0" encoding="UTF-8"?>
<Person>
  <Name>John</Name>
  <Surname>Doe</Surname>
  . . .
</Person>

I can make the web service return text/xml data as requested forcing it in the ConfigureServices method inside Startup.cs like following:

public void ConfigureServices(IServiceCollection services)
{
    services.AddControllers();
    services.AddMvc(options =>
    {
        options.Filters.Add(new ProducesAttribute("text/xml"));
    }).AddXmlSerializerFormatters();
}

The problem is that when I call the method that should return data I don't have the XML declaration header, required by the customer for some reason:

<?xml version="1.0" encoding="UTF-8"?>

This is the result:

<Person xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
    <Name>John</Name>
    <Surname>Doe</Surname>
</Person>

Here is the method:

[HttpGet("getperson")]
public Person GetPerson()
{
    return new Person 
    {
        Name = "John",
        Surname = "Doe",
    };        
}

And here the class Person:

public class Person
{
    public string Name { get; set; }
    public string Surname { get; set; }
}

I researched a lot, but everything I found didn't help me at all. I'd like to use the framework's features serializing my classes instead of having to build the XML structure node by node, so I was hoping in some settings inside the services that would allow me to do so.

Any changes to the GetPerson method can be done if necessary, this is just a really simplified test.

Thank you in advance for the help!

like image 854
Belfed Avatar asked Aug 07 '26 00:08

Belfed


1 Answers

You need to configure XML output formatter like this:

public void ConfigureServices(IServiceCollection services)
{
    services.AddControllers();
    services.AddMvc(options =>
    {
        options.Filters.Add(new ProducesAttribute("text/xml"));
        options.OutputFormatters.Add(new XmlSerializerOutputFormatter(new XmlWriterSettings
        {
            OmitXmlDeclaration = false
        }));
    }).AddXmlSerializerFormatters();
}

Sample output:

<?xml version="1.0" encoding="utf-8"?>
<ArrayOfString xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
    <string>value1</string>
    <string>value2</string>
</ArrayOfString>
like image 150
Tearth Avatar answered Aug 09 '26 23:08

Tearth



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!