MVC调用WebApi接口怎么写
在MVC中调用WebApi接口,可以使用HttpClient类来发起请求。具体步骤如下:
-
在MVC项目中添加HttpClient的NuGet包。
-
在Controller中创建HttpClient对象,并设置BaseAddress为WebApi的地址。
private HttpClient client = new HttpClient();
client.BaseAddress = new Uri("http://localhost:8080/api/");
- 发起请求,获取响应结果。
HttpResponseMessage response = await client.GetAsync("users");
if (response.IsSuccessStatusCode)
{
var users = await response.Content.ReadAsAsync<List<User>>();
return View(users);
}
else
{
return View("Error");
}
其中,GetAsync方法的参数为WebApi的请求路径,ReadAsAsync方法用于将响应结果转换成指定类型的对象。如果响应状态码为成功,则将结果传递给View,否则返回错误视图。
原文地址: https://www.cveoy.top/t/topic/biZx 著作权归作者所有。请勿转载和采集!