四、添加HttpClient实现Blazor Server与Web Api之间的通信

7 篇文章 0 订阅
7 篇文章 0 订阅

四、添加HttpClient实现Blazor Server与Web Api之间的通信

以下代码及配置均在Blazor Server应用项目中添加:

  1. 添加WebApi环境信息到appsetting.Development.json;

    {
      "DetailedErrors": true,
      "Logging": {
        "LogLevel": {
          "Default": "Information",
          "Microsoft.AspNetCore": "Warning"
        }
      },
      "WebApi":{
        "Name":"TeachingWebApi",
        "Url":"http://localhost:",
        "Port":"5211"
      }
    }
    
  2. 添加以下代码到Program.cs文件;

    builder.Services.AddScoped(sp =>
        new HttpClient
        {
            BaseAddress = new Uri(builder.Configuration["WebApi"] ?? "http://localhost:5211")
        });
    
  3. 添加一个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();
            }
        }
    }
    
  4. 添加HealthCheckManager的实例到_Imports.razor,以向razor页面提供实例;

    @using TeachingBlazorApp.Infrastructure.Managers
    
    @inject HealthCheckManager _healthCheckManager;
    
  5. 如果出现该错误: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>();
    
  6. 修改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();
        }
    }
    
    
  7. 按照之前教程先运行WebApi应用,再运行BlazorServer应用,浏览器自动打开BlazorServer和WebApi Swagger应用网页:

    可以看到BlazorServer通过HttpClient从WebApi获取字段并展示在页面上:
    运行成功

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值