How to return JSON from MVC WEB API Controller

I understand that the WEB API uses content negotiation for Accept-Content-Type to return json or xml. This is not good enough, and I need to pragmatically decide if I want to return json or xml.

Outdated examples of using the HttpResponseMessage<T> , which is no longer present in MVC 4, are flooded on the Internet.

  tokenResponse response = new tokenResponse(); response.something = "gfhgfh"; if(json) { return Request.CreateResponse(HttpStatusCode.OK, response, "application/json"); } else { return Request.CreateResponse(HttpStatusCode.OK, response, "application/xml"); } 

How to change the above code so that it works?

+8
asp.net-mvc asp.net-mvc-4
source share
1 answer

Try it like this:

 public HttpResponseMessage Get() { tokenResponse response = new tokenResponse(); response.something = "gfhgfh"; if(json) { return Request.CreateResponse(HttpStatusCode.OK, response, Configuration.Formatters.JsonFormatter); } else { return Request.CreateResponse(HttpStatusCode.OK, response, Configuration.Formatters.XmlFormatter); } } 

or even better, in order to avoid cluttering your controller with such a water network infrastructure code, you could also write your own media format and run this test inside it.

+23
source share

All Articles