Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to return JSON from MVC WEB API Controller

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

The internet is flooded with obsolete examples of using HttpResponseMessage<T>, which is no longer present in MVC 4.

    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 do I change the above code so that it works?

like image 286
user1662812 Avatar asked Oct 03 '12 09:10

user1662812


People also ask

How do I return a JSON response in API?

To return JSON from the server, you must include the JSON data in the body of the HTTP response message and provide a "Content-Type: application/json" response header. The Content-Type response header allows the client to interpret the data in the response body correctly.

How can I get data from Web API in MVC controller?

First of all, create MVC controller class called StudentController in the Controllers folder as shown below. Right click on the Controllers folder > Add.. > select Controller.. Step 2: We need to access Web API in the Index() action method using HttpClient as shown below.


1 Answers

Try 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, to avoid cluttering your controller with such plumbing infrastructure code you could also write a custom media formatter and perform this test inside it.

like image 89
Darin Dimitrov Avatar answered Sep 24 '22 06:09

Darin Dimitrov