The API I'm building returns json almost everywhere, but I sometimes need to return xml with a custom formatter.
I created a custom formatter (I didn't copy the WriteResponseBodyAsync
to keep it shorter)
public class XmlOutputFormatter : TextOutputFormatter
{
public XmlOutputFormatter()
{
SupportedMediaTypes.Add(MediaTypeHeaderValue.Parse("application/xml"));
SupportedEncodings.Add(Encoding.UTF8);
SupportedEncodings.Add(Encoding.Unicode);
}
protected override bool CanWriteType(Type type)
{
return true; // I tried doing this to force it to work on any type,
// but I don't think it's needed
}
public override bool CanWriteResult(OutputFormatterCanWriteContext context)
{
if (context == null)
throw new ArgumentNullException(nameof(context));
return context.ContentType.ToString() == "application/xml";
}
}
It works when I have
[Produces("application/xml")]
on a controller method, but when I don't use this and ask for xml in postman using the Accept:application/xml
header it still returns json.
I added the formatter in Startup.cs like so:
services
.AddMvc(options =>
{
options.OutputFormatters.Add(new XmlOutputFormatter());
});
I know the formatter works the issue is that asp seems to ignore the Accept header and always returns json. I know I could simply force it to return xml, but I would prefer returning xml.
I know there is a default xml formatter, but it doesn't behave exactly like I need it to.
I'm using asp.net core 2.0 and visual studio professional 2017 15.3 preview 6