15
[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();
2
  • are you declaring this two attributes together [HttpGet] [HttpPost] ? Commented Dec 5, 2019 at 8:03
  • 1
    ASP.NET Core is a different beast to the old Web API, it does not natively work with or understand HttpResponseMessage. I also made the migration from web API -> Core and had to unlearn a lot of things like that before it started making sense to me. Commented Dec 5, 2019 at 8:24

3 Answers 3

26

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

Comments

6
  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?

Comments

2

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());
    });
}

Comments

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.