[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();
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 { ... }
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.
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
};
}
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?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With