3

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!

1 Answer 1

8

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>
Sign up to request clarification or add additional context in comments.

1 Comment

HA! I knew there was something I could do inside the MVM options, I just coulnd't find it... I tried and it actually works, thank you very much!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.