In web api 2 controller handling request with "Accept: application/xml" header field.
public class ConverterController : ApiController
{
class A {}
public class B {}
public class C : Exception {}
public IHttpActionResult Action()
{
var res = Request.CreateResponse(HttpStatusCode.Ok, new A());
// res.Content.Headers.ContentType.MediaType == "application/json"
var res = Request.CreateResponse(HttpStatusCode.Ok, new B());
// res.Content.Headers.ContentType.MediaType == "application/xml"
var res = Request.CreateResponse(HttpStatusCode.Ok, new C());
// res.Content.Headers.ContentType.MediaType == "application/json"
}
}
Why class A and C is serializing to json?
It turns out that when there is an exception in XML serializer web api 2 silently falls back to JSON serializer. Thanks to AarónBC for the hint that must force XML serializer to get serialization exception.
var res = Request.CreateResponse(HttpStatusCode.OK, new C(), Configuration.Formatters.XmlFormatter);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.