四、添加HttpClient实现Blazor Server与Web Api之间的通信
以下代码及配置均在Blazor Server应用项目中添加:
-
添加WebApi环境信息到appsetting.Development.json;
{ "DetailedErrors": true, "Logging": { "LogLevel": { "Default": "Information", "Microsoft.AspNetCore": "Warning" } }, "WebApi":{ "Name":"TeachingWebApi", "Url":"http://localhost:", "Port":"5211" } }
-
添加以下代码到Program.cs文件;
builder.Services.AddScoped(sp => new HttpClient { BaseAddress = new Uri(builder.Configuration["WebApi"] ?? "http://localhost:5211") });
-
添加一个HealthCheckManager,负责调用API的处理;
namespace TeachingBlazorApp.Infrastructure.Managers { public class HealthCheckManager { private readonly HttpClient _httpClient; public HealthCheckManager(HttpClient httpClient) { _httpClient = httpClient; } public async Task<string> GetDataAsync() { var response = await _httpClient.GetAsync("api/healthcheck"); return response.Content.ToString(); } } }
-
添加HealthCheckManager的实例到_Imports.razor,以向razor页面提供实例;
@using TeachingBlazorApp.Infrastructure.Managers @inject HealthCheckManager _healthCheckManager;
-
如果出现该错误:InvalidOperationException: Cannot provide a value for property ‘_healthCheckManager’ on type ‘TeachingBlazorApp.App’. There is no registered service of type ‘TeachingBlazorApp.Infrastructure.Managers.HealthCheckManager’.
则需要在Program.cs里加入以下代码:
// Register Services builder.Services.AddScoped<HealthCheckManager>();
-
修改index.razor
@page "/" <h1>@response</h1> @code { private string response; protected override async Task OnAfterRenderAsync(bool firstRender) { if (firstRender) { await GetAsync(); StateHasChanged(); } } private async Task GetAsync() { response = await _healthCheckManager.GetDataAsync(); } }
-
按照之前教程先运行WebApi应用,再运行BlazorServer应用,浏览器自动打开BlazorServer和WebApi Swagger应用网页:
可以看到BlazorServer通过HttpClient从WebApi获取字段并展示在页面上: