narouz
narouz

Reputation: 215

How to make ASP.NET Core return XML result?

[HttpGet]
[HttpPost]
public HttpResponseMessage GetXml(string value)
{
    var xml = $"<result><value>{value}</value></result>";
    return new HttpResponseMessage
   {
       Content = new StringContent(xml, Encoding.UTF8, "application/xml")
   };
}

I called the action using Swagger and passed this parameter 'text value'

Expected result should be an XML file like this: text value

Actual Result: strange json result without the passed value! https://www.screencast.com/t/uzcEed7ojLe

I tried the following solutions but did not work:

services.AddMvc().AddXmlDataContractSerializerFormatters();
services.AddMvc().AddXmlSerializerFormatters();

Upvotes: 14

Views: 20047

Answers (3)

Salah Akbari
Salah Akbari

Reputation: 39956

For ASP.NET core 2+, you need to configure XmlDataContractSerializerOutputFormatter, it could be found from Nuget:

public void ConfigureServices(IServiceCollection services)
{
    services.AddMvc(c =>
    {
        c.OutputFormatters.Add(new XmlDataContractSerializerOutputFormatter());
    });
}

Upvotes: 2

phonemyatt
phonemyatt

Reputation: 1377

  1. you are missing parameter in your attribute.
  2. you can put produces attribute to declare what type of output format
  3. you can embrace IActionResult or directly return ContentResult.

    [HttpGet("{value}")]
    [Produces("application/xml")]
    public IActionResult GetXml(string value)
    {
        var xml = $"<result><value>{value}</value></result>";
        //HttpResponseMessage response = new HttpResponseMessage();
        //response.Content = new StringContent(xml, Encoding.UTF8);
        //return response;
    
        return new ContentResult{
            ContentType = "application/xml",
            Content = xml,
            StatusCode = 200
        };
    }
    

The above will give you

<result>
    <value>hello</value>
</result>

you can refer to following link to understand more about IActionResult

What should be the return type of WEB API Action Method?

Upvotes: 6

Ⲁⲅⲅⲉⲗⲟⲥ
Ⲁⲅⲅⲉⲗⲟⲥ

Reputation: 668

Try this solution

[HttpGet]
[HttpPost]
public ContentResult GetXml(string value)
{
    var xml = $"<result><value>{value}</value></result>";
    return new ContentResult
    {
        Content = xml,
        ContentType = "application/xml",
        StatusCode = 200
    };
}

Upvotes: 25

Related Questions