In my project with netcore 2.2 I use this code:
[HttpGet]
[Route( "something" )]
public IActionResult GetSomething()
{
string payload = "Something";
OkObjectResult result = Ok( payload );
// currently result.Formatters is empty but we'd like to ensure it will be so in the future
result.Formatters.Clear();
// force response as xml
result.Formatters.Add( new Microsoft.AspNetCore.Mvc.Formatters.XmlSerializerOutputFormatter() );
return result;
}
It forces only one action within a controller to return a xml without effect to other actions. Also this code doesn't contain neither HttpResponseMessage or StringContent or ObjectContent which are disposable objects and hence should be handled appropriately (it is especially a problem if you use any of code analyzers that reminds you about it).
Going further you could use a handy extension like this:
public static class ObjectResultExtensions
{
public static T ForceResultAsXml<T>( this T result )
where T : ObjectResult
{
result.Formatters.Clear();
result.Formatters.Add( new Microsoft.AspNetCore.Mvc.Formatters.XmlSerializerOutputFormatter() );
return result;
}
}
And your code will become like this:
[HttpGet]
[Route( "something" )]
public IActionResult GetSomething()
{
string payload = "Something";
return Ok( payload ).ForceResultAsXml();
}
In addition, this solution looks like an explicit and clean way to force return as xml and it is easy to add to your existent code.
P.S. I used fully-qualified name Microsoft.AspNetCore.Mvc.Formatters.XmlSerializerOutputFormatter just to avoid ambiguity.