1

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");
    }

1 Answer 1

4

How about this.

string json = await response.Content.ReadAsStringAsync();
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks! After I added the async keyword to the method and made it return Task<ActionResult>, it works.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.