stackdisplay
stackdisplay

Reputation: 2045

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

Upvotes: 11

Views: 27877

Answers (2)

Hiren Patel
Hiren Patel

Reputation: 317

Here below an example of inserting log for action.

    [HttpPost]
    public async System.Threading.Tasks.Task<ActionResult> ChangePassword(ChangePasswordInfo model)
    {
        var omodelPwd = loginContext.UsersChangePasswordRequest(objAuthModel.oUsers.iID);

        TempData[LKTransferDashboardCommon.Notification] = JsonConvert.SerializeObject(new Response { Success = false, ResponseString = "Invalid Old Password!" });
        var auditLog = LKTransferDashboardCommon.PrepareAuditLogData(
                                           "ChangePassword-Fail",
                                           objAuthModel.oUsers.iID,
                                           nameof(ChangePassword),
                                           Request.ServerVariables["REMOTE_ADDR"],
                                           "AdministrationController",
                                           objAuthModel.oUsers.Name
                                       );
         await AuditLogHelper.ExecuteAsync(auditLog, null, null, null, null, null).ConfigureAwait(false);

         return View(model);
     }

Upvotes: 0

hivo
hivo

Reputation: 311

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

Upvotes: 22

Related Questions