You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Blazor中OnInitializedAsync内HttpClient调用报错问题咨询

HttpClient URI无效异常:原因分析与解决方案

问题重现

配置代码(Program.cs)

using Microsoft.AspNetCore.Components.WebAssembly.Hosting;
using Microsoft.Extensions.DependencyInjection.Extensions;

var builder = WebAssemblyHostBuilder.CreateDefault(args);

builder.Services.TryAddScoped(sp => new HttpClient { BaseAddress = new Uri("https://localhost:7224/") });

await builder.Build().RunAsync();

组件调用代码

var res = await _httpClient.GetFromJsonAsync<List<Product>>("api/User");

报错信息

System.InvalidOperationException:An invalid request URI was provided. Either the request URI must be an absolute URI or BaseAddress must be set.

核心原因

所谓“添加异常捕获后恢复正常”是假象:异常依然会发生,只是被捕获后程序未崩溃,你看不到显性错误提示,但请求实际并未成功(res大概率为null)。

触发报错的真实原因通常是以下两点:

  1. HttpClient实例未被正确注入:你使用了TryAddScoped,该方法仅在服务未注册时才添加实例。如果项目中其他地方已经注册过HttpClient,你配置的带BaseAddress的实例会被忽略,导致注入的HttpClient没有BaseAddress,调用相对路径时触发URI无效异常。
  2. BaseAddress配置存在硬编码风险:固定写死的地址可能在部署场景中不可用,但这种问题不会因异常捕获而消失。

解决方案

1. 强制注册HttpClient,覆盖默认配置

将TryAddScoped替换为AddScoped,确保你的配置生效,同时推荐使用宿主环境的BaseAddress避免硬编码:

builder.Services.AddScoped(sp => new HttpClient { BaseAddress = new Uri(builder.HostEnvironment.BaseAddress) });

2. 验证组件注入逻辑

确保组件中通过构造函数正确注入HttpClient,不要手动创建实例:

private readonly HttpClient _httpClient;

public YourComponent(HttpClient httpClient)
{
    _httpClient = httpClient;
}

3. 正确处理异常(而非掩盖)

异常捕获的作用是处理失败场景,不是掩盖配置错误。建议在捕获时明确处理不同异常类型:

protected override async Task OnInitializedAsync()
{
    try
    {
        var res = await _httpClient.GetFromJsonAsync<List<Product>>("api/User");
        if (res != null)
        {
            // 处理返回数据
        }
    }
    catch (InvalidOperationException ex)
    {
        // 处理BaseAddress未配置的情况,比如提示用户或记录日志
    }
    catch (HttpRequestException ex)
    {
        // 处理网络请求失败的情况
    }
}

内容的提问来源于stack exchange,提问作者user24622900

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.24 18:42:53