Asp.net-Mvc

從 mvc 控制器使用 web api 時返回 json 結果

  • May 20, 2019

我正在通過帶有 HttpClient 的 mvc 控制器使用外部 Web api。我的 web api 確實返回 json 格式的內容。

如何在使用 web api 時在我的 mvc 控制器中返回相同的 json 格式的 web api 響應內容?我期待這樣的事情。

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

使用 Json.Net 你可以做這樣的事情:

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

下面是一個插入日誌以執行操作的範例。

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

引用自:https://stackoverflow.com/questions/34303746