Return "application/xml" instead of "text/plain" ASP.NET Core Web API
You could do return Content(xmlString, "application/xml")
but that's probably not the best way to do it, unless they are stored in this way on the filesystem or DB.
Usually you would want to have strong typed classes which you return from your actions and have them serialize it as xml.
You can also tell your actions to return the content based on the accept header (i.e. either json or xml) but for xml you need to register the xml serializers first iirc.
services.AddMvc(...)
.AddXmlSerializerFormatters()
.AddXmlDataContractSerializerFormatters();
and annotate your actions
[Produces("application/json", "application/xml")]
public Task<IActionResult> Get()
{
User user = ...........;
return ObjectResult(user);
}
If the client sends Accept: application/xml
then it will return xml and if the client sends Accept: application/json
it returns json.
Short Answer
If you have a string that is XML and need to return it as an XML document, then return a ContentResult.
[HttpGet]
public ContentResult Get()
{
return new ContentResult
{
ContentType = "application/xml",
Content = xmlString,
StatusCode = 200
};
}
Full Example
Controller
using Microsoft.AspNetCore.Mvc;
namespace MyXmlSample
{
[Route("xml")]
public class MyXmlController
{
public static string xmlString =
@"<?xml version=""1.0"" encoding=""UTF-8""?>
<sample>
Hello World.
</sample>";
[HttpGet]
public ContentResult Get()
{
return new ContentResult
{
ContentType = "application/xml",
Content = xmlString,
StatusCode = 200
};
}
}
}
Startup
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.DependencyInjection;
namespace MyXmlSample
{
public class Program
{
public void ConfigureServices(IServiceCollection services)
{
services.AddMvcCore();
}
public void Configure(IApplicationBuilder app)
{
app.UseMvc();
}
public static void Main(string[] args)
{
var host = new WebHostBuilder()
.UseKestrel()
.UseStartup<Program>()
.Build();
host.Run();
}
}
}
project.json
{
"version": "1.0.0-*",
"compilationOptions": {
"emitEntryPoint": true
},
"dependencies": {
"Microsoft.AspNetCore.Mvc.Core": "1.0.0-*",
"Microsoft.AspNetCore.Server.Kestrel": "1.0.0-*",
"Microsoft.NETCore.App": "1.0.0-rc2-*"
},
"frameworks": {
"netcoreapp1.0": {
"imports": [
"dnxcore50",
"portable-net45"
]
}
},
"runtimes": {
"win10-x64": {}
}
}
Response
HTTP/1.1 200 OK
Date: Sun, 17 Apr 2016 22:10:45 GMT
Content-Type: application/xml
Server: Kestrel
Content-Length: 75
<?xml version="1.0" encoding="UTF-8"?>
<sample>
Hello World.
</sample>
Here it is on GitHub for good measure. :)