MVC怎么调用API里的接口 MVC视图怎么显示些用户信息
MVC调用API接口:
- 首先在MVC的控制器中引入API的命名空间和类,如:
using System.Net.Http;
using Newtonsoft.Json;
using MyAPI.Models;
- 在控制器中实例化HttpClient类,调用API接口,如:
using (HttpClient client = new HttpClient())
{
client.BaseAddress = new Uri("http://localhost:1234/api/"); //API地址
HttpResponseMessage response = await client.GetAsync("userinfo"); //调用API接口
if (response.IsSuccessStatusCode)
{
string content = await response.Content.ReadAsStringAsync();
UserInfo userInfo = JsonConvert.DeserializeObject<UserInfo>(content); //将返回的JSON数据转换为UserInfo对象
ViewBag.UserName = userInfo.UserName; //将用户名传递给视图
}
}
- 将获取到的数据传递给视图,如上述代码中使用了ViewBag将用户名传递给视图。
MVC视图显示用户信息:
- 在视图中引用控制器中传递的数据,如:
<h2>Welcome, @ViewBag.UserName</h2>
- 按照需要使用HTML元素和CSS样式来美化用户信息的显示效果,如:
<div class="user-info">
<h2>Welcome, @ViewBag.UserName</h2>
<p>Age: @Model.Age</p>
<p>Email: @Model.Email</p>
</div>
原文地址: https://www.cveoy.top/t/topic/bi8m 著作权归作者所有。请勿转载和采集!