【发布时间】:2016-06-22 03:28:15
【问题描述】:
我使用 mvc 项目和 web api 单独的项目创建了一个 web 应用程序,我使用身份来注册用户。 我的问题是当 web api 返回结果时如何在 MVC 视图中显示它
这是我的 web api 控制器 -
public async Task<IHttpActionResult> Register(RegisterBindingModel model)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
var user = new ApplicationUser() { UserName = model.Email, Email = model.Email };
IdentityResult result = await UserManager.CreateAsync(user, model.Password);
if (!result.Succeeded)
{
return GetErrorResult(result);
}
}
这就是我如何调用这个 web api -
public async Task<ActionResult> Register(RegisterView model)
{
//
HttpClient client = new HttpClient();
//The URL of the WEB API Service
string url = "http://localhost:51493/Api/Account/Register";
client.BaseAddress = new Uri(url);
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
//
HttpResponseMessage responseMessage = await client.PostAsJsonAsync(url, model);
if (responseMessage.IsSuccessStatusCode)
{
return RedirectToAction("Index");
}
else{//pass the validation errors in view and display it in view}
}
}
如何做到这一点?
【问题讨论】:
-
您将 Web api 调用的结果作为模型或模型的一部分传递给您要在其中显示它的视图。它与使用任何其他外部数据块没有什么不同你想在你的视图中显示。不同的是,您也应该能够使用客户端代码访问 Web API 而不是返回服务器来完成此操作。
-
你能否在代码的帮助下详细说明我是一个 .net 框架的初学者,谢谢 :)
-
那么我建议你阅读一些关于 MVC 工作原理以及如何在视图中显示数据的教程或书籍。
标签: .net model-view-controller asp.net-web-api