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!