前言
ASP.NET Core MVC 是使用“模型-视图-控制器”设计模式构建 Web 应用和 API 的丰富框架。模型-视图-控制器 (MVC) 体系结构模式将应用程序分成 3 个主要组件组:模型、视图和控制器。
当前主要实现创建MVC模板作为前端项目,并访问后端WebApi服务。
一、创建MVC项目
项目模板里主要有Data,Models,Views三个文件夹(对应MVC)。
二、添加控制器
MVC模板的控制器继承类(Controller)和WebApi(ControllerBase)的控制器不一致,MVC的控制器功能多了对View的控制。
public class ShirtController : Controller
{
public IActionResult Index()
{
return View();
}
}
三、使用强类型模型
MVC 提供将强类型模型对象传递给视图的功能。
为了方便数据展示,直接使用@model 指令进行强类型模型绑定,还有其他传递数据的方式。
在Views文件夹下新建Shirt文件夹的Index.cshtml文件,路由规则会根据控制器的名称和方法名解析对应的视图文件。
@model List<Shirt>
<h3>Shirts</h3>
<br />
<table class="table table-striped">
<thead>
<tr>
<td>Brand</td>
<td>Gender</td>
<td>Color</td>
<td>Size</td>
<td>Price</td>
</tr>
</thead>
<tbody>
@foreach (var shirt in Model)
{
<tr>
<td>@shirt.Brand</td>
<td>@shirt.Gender</td>
<td>@shirt.Color</td>
<td>@shirt.Size</td>
<td>@shirt.Price</td>
</tr>
}
</tbody>
</table>
四、使用Api请求类
1. 安装包
使用Nuget安装Microsoft.Extensions.Http包。
2. 添加客户端
在Program.cs文件中添加客户端。
builder.Services.AddHttpClient("ShirtApi", client =>
{
client.BaseAddress = new Uri("https://localhost:7247/api/");
client.DefaultRequestHeaders.Add("accept", "application/json");
});
3. 创建WebApi访问类
创建http请求,访问WecApi获取数据。并且提取类生成接口。
public class WebApiExecuter : IWebApiExecuter
{
private const string apiName = "ShirtApi";
private readonly IHttpClientFactory httpClientFactory;
public WebApiExecuter(IHttpClientFactory httpClientFactory)
{
this.httpClientFactory = httpClientFactory;
}
public async Task<T?> InvokeGet<T>(string relativeUrl)
{
var httpClient = httpClientFactory.CreateClient(apiName);
return await httpClient.GetFromJsonAsync<T>(relativeUrl);
}
}
4. 注册使用WebApi访问类
同样在program.cs中注册,在controller中使用。
public class ShirtController : Controller
{
private readonly IWebApiExecuter webApiExecuter;
public ShirtController(IWebApiExecuter webApiExecuter)
{
this.webApiExecuter = webApiExecuter;
}
public async Task<IActionResult> Index()
{
return View(await webApiExecuter.InvokeGet<List<Shirt>>("shirt"));
}
}