我正在通过带有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();
}
}
}
答案 0 :(得分:5)
使用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));
}
答案 1 :(得分:0)
下面是为操作插入日志的示例。
[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);
}