09前端访问WebApi - ASP.NET Core MVC


前言

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"));
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值