Thea
Thea

Reputation: 161

How to get the JSON string from a Web API response

I have a ASP.NET MVC 4 application where I have a controller whith an action that recieves XHR requests and returns JSON. In this action I want to make a call to a WEB API, recieve the response as JSON and use the JSON string as the actions return value.

(And I'm not allowed to call the WEB API directly with javascript, I need to go via the server)

I manage to make the request to the Web API but I can't figure out how to read out the JSON string.

Here is my method:

  public ActionResult Index()
    {
        String ret = "";  
            HttpClient client = new HttpClient();
            client.BaseAddress = new Uri("http://localhost:8080/");

            client.DefaultRequestHeaders.Accept.Add(
                new MediaTypeWithQualityHeaderValue("application/json"));

            HttpResponseMessage response = client.GetAsync("api/stuff").Result;  
            if (response.IsSuccessStatusCode)
            {
                // How do I get the JSON string out of the response object?
                //ret = response.??
            }
            else
            {                     
            }

            return Content(ret, "application/json");
    }

Upvotes: 1

Views: 2975

Answers (1)

PeaceFrog
PeaceFrog

Reputation: 717

How about this.

string json = await response.Content.ReadAsStringAsync();

Upvotes: 4

Related Questions