Asp.net mvc 从mvc控制器使用web api时返回json结果
我通过带有HttpClient的mvc控制器使用外部web api。我的web api确实返回json格式的内容 在使用web api时,如何在mvc控制器中返回相同json格式的web api响应内容?我期待着这样的事情Asp.net mvc 从mvc控制器使用web api时返回json结果,asp.net-mvc,c#-4.0,asp.net-web-api,asp.net-web-api2,Asp.net Mvc,C# 4.0,Asp.net Web Api,Asp.net Web Api2,我通过带有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);
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));
}
公共异步任务GetUserMenu()
{
字符串结果=string.Empty;
使用(HttpClient=new HttpClient())
{
client.BaseAddress=新Uri(url);
HttpResponseMessage response=wait client.GetAsync(url);
if(响应。IsSuccessStatusCode)
{
结果=wait response.Content.ReadAsStringAsync();
}
}
返回Json(Newtonsoft.Json.JsonConvert.DeserializeObject(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);
}
[HttpPost]
public async System.Threading.Tasks.Task ChangePassword(ChangePasswordInfo模型)
{
var omodelPwd=loginContext.UsersChangePasswordRequest(objAuthModel.oUsers.iID);
TempData[LKTransferDashboardCommon.Notification]=JsonConvert.SerializeObject(新响应{Success=false,ResponseString=“旧密码无效!”);
var auditLog=LKTransferDashboardCommon.PrepareAuditLogData(
“更改密码失败”,
objAuthModel.oUsers.iID,
姓名(更改密码),
Request.ServerVariables[“REMOTE\u ADDR”],
“管理控制器”,
对象模型.oUsers.Name
);
await AuditLogHelper.ExecuteAsync(auditLog,null,null,null,null).ConfigureAwait(false);
返回视图(模型);
}