Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Returning json result while consuming web api from mvc controller

I am consuming an external web api through mvc controller with HttpClient. My web api do return json-formatted content.

How do i return the same json-formatted content of web api response in my mvc controller while consuming the web api? I am expecting something like this.

public async JsonResult GetUserMenu()
{
    using (HttpClient client = new HttpClient())
    {
        client.BaseAddress = new Uri(url);
        HttpResponseMessage response = await client.GetAsync(url);

        if (response.IsSuccessStatusCode)
        {
             return await response.Content.ReadAsJsonAsync();
        }
    }
}
like image 667
stackdisplay Avatar asked Dec 16 '15 04:12

stackdisplay


1 Answers

Using Json.Net you could do something like this:

public async Task<JsonResult> GetUserMenu()
{
    string result = string.Empty;

    using (HttpClient client = new HttpClient())
    {
        client.BaseAddress = new Uri(url);
        HttpResponseMessage response = await client.GetAsync(url);

        if (response.IsSuccessStatusCode)
        {
            result = await response.Content.ReadAsStringAsync();
        }
    }

    return Json(Newtonsoft.Json.JsonConvert.DeserializeObject<dynamic>(result));
}
like image 67
hivo Avatar answered Sep 30 '22 11:09

hivo