Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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();
like image 411
narouz Avatar asked Dec 05 '19 07:12

narouz


People also ask

How do I return XML and JSON from Web API in .NET core?

In order to return XML using an IActionResult method, you should also use the [Produces] attribute, which can be set to “application/xml” at the API Controller level. [Produces("application/xml")] [Route("api/[controller]")] [ApiController] public class LearningResourcesController : ControllerBase { ... }

How does Web API send XML data?

If you want to send XML data to the server, set the Request Header correctly to be read by the sever as XML. xmlhttp. setRequestHeader('Content-Type', 'text/xml'); Use the send() method to send the request, along with any XML data.


2 Answers

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
    };
}
like image 148
Ⲁⲅⲅⲉⲗⲟⲥ Avatar answered Oct 21 '22 01:10

Ⲁⲅⲅⲉⲗⲟⲥ


  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?

like image 41
phonemyatt Avatar answered Oct 21 '22 03:10

phonemyatt