In one of my recent projects at work, I have to build a web API which simply returns a XML string as raw XML in the response. The response header also needs to have a content type of text/xml. The endpoint will always returns XML, result is already an XML string and not some objects so I wouldn’t need to register a XmlMediaTypeFormatter to serialise it. It just returns the result string as is.
Typically, the controller action would return result directly or you pass your result in Ok method if your controller action returns an IActionResult. The media type formatter will then serialise it according to the content type specified in the request headers. However, you could return ContentResult instead. Content result allows you to specify the content of your response body as string and the content type manually.
[ApiController]
[Route("[controller]")]
public class SampleController : ControllerBase
{
[HttpPost]
public IActionResult Post()
{
var result = "<AAA><BBB>This is a test</BBB></AAA>";
return new ContentResult
{
Content = result,
ContentType = "text/xml",
StatusCode = (int)HttpStatusCode.OK
};
}
}
This is the response you get when calling this endpoint

