How to response with text/xml media type in ASP.NET Web Api



Here is my api action:



[HttpGet]
public IHttpActionResult Get()
{
HttpContext.Current.Response.ContentType = "text/xml";
string foo = GetXmlString();
return Ok(foo);
}


I wish the response can return "text/xml" type when the related request happens. If I do nothing (use default configuration), the return type would be "application/xml", if I did following configuration:



var applicationXml = config.Formatters.XmlFormatter.SupportedMediaTypes.FirstOrDefault(_ => _.MediaType == "application/xml");
config.Formatters.XmlFormatter.SupportedMediaTypes.Remove(applicationXml);
var textXml = config.Formatters.XmlFormatter.SupportedMediaTypes.FirstOrDefault(_ => _.MediaType == "text/xml");
if (textXml == null)
{
config.Formatters.XmlFormatter.SupportedMediaTypes.Add(new MediaTypeHeaderValue("text/xml"));
}


It would use "application/json" instead. But I don't want to remove "application/json", which is the default media type.


And why the action level config cannot be applied as expected, but use the global one? I am quite confused with this behavior.


No comments:

Post a Comment