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

.NET 7 Blazor Server API路由问题:相对URI请求失败怎么解决

Blazor Server 相对URI调用API报错的解决方案

问题场景

在.NET 7 Blazor Server应用中添加ProductController后,使用相对URI api/Product调用接口时抛出错误:

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

使用完整绝对URI https://localhost:7157/api/Product调用则正常。

相关代码示例

控制器代码

[Route("api/[controller]")]
[ApiController]
public class ProductController : ControllerBase
{
    private static List<Product> Products = new List<Product>
        {
            new Product { Id = 1, Title = "Die Cut", Description="Die Cut Sticker Cut around the outer edege of the design.",Image="./Images/DieCut.jpg", Price= 2.99m },
            new Product { Id = 2, Title = "Circle Cut", Description="Round Sticker With Your Design In The Center.",Image="./Images/OvalCut.jpg", Price= 2.99m },
            new Product { Id = 3, Title = "Square Cut", Description="Square Sticker With Your Design In The Center.",Image="./Images/SquareCut.jpg", Price= 3.99m },
            new Product { Id = 4, Title = "Oval Cut", Description="Oval Sticker With Your Design In The Center.",Image="./Images/OvalCut.jpg", Price= 4.99m },
            new Product { Id = 5, Title = "Clear Back", Description="Die Cut Sticker Cut Around The Outer Edege Of The Design On Clear Material.",Image="./Images/ClearDieCut.jpg", Price= 5.99m },
            new Product { Id = 5, Title = "Glow In The Dark", Description="Any Cut Type On Glow In The Dark Material.",Image="./Images/GlowInDark.jpg", Price= 6.99m },
        };

    [HttpGet]
    public async Task<IActionResult> GetProducts()
    {
        return Ok(Products);
    }
}

相对URI调用代码(报错)

protected override async Task OnInitializedAsync()
{
    var result = await Http.GetFromJsonAsync<List<Product>>("api/Product");

    if (result != null)
    {
        Products = result;
    }
}

绝对URI调用代码(正常)

private static List<Product> Products = new List<Product>();

protected override async Task OnInitializedAsync()
{
    var result = await Http.GetFromJsonAsync<List<Product>>("https://localhost:7157/api/Product");

    if (result != null)
    {
        Products = result;
    }
}

问题分析

这不是路由问题,错误提示已经明确指出核心原因:注入的HttpClient实例未配置BaseAddress,导致无法将相对URI解析为完整的绝对地址。Blazor Server中默认注入的HttpClient不会自动设置BaseAddress,因此直接使用相对路径会触发该错误。

解决方案

方案1:配置命名HttpClient的BaseAddress

在Program.cs中注册带有BaseAddress的命名HttpClient:

builder.Services.AddHttpClient("ApiClient", client =>
{
    client.BaseAddress = new Uri(builder.HostEnvironment.BaseAddress);
});

在组件中注入IHttpClientFactory并创建命名客户端:

@inject IHttpClientFactory HttpClientFactory

protected override async Task OnInitializedAsync()
{
    var apiClient = HttpClientFactory.CreateClient("ApiClient");
    var result = await apiClient.GetFromJsonAsync<List<Product>>("api/Product");
    if (result != null)
    {
        Products = result;
    }
}

方案2:通过NavigationManager拼接绝对地址

如果不想配置命名客户端,可以利用NavigationManager获取当前应用的基础地址,拼接成完整URI:

@inject NavigationManager NavManager
@inject HttpClient Http

protected override async Task OnInitializedAsync()
{
    var fullApiUri = new Uri(new Uri(NavManager.BaseUri), "api/Product");
    var result = await Http.GetFromJsonAsync<List<Product>>(fullApiUri.AbsoluteUri);
    if (result != null)
    {
        Products = result;
    }
}

方案3:全局配置默认HttpClient的BaseAddress

直接为默认注入的HttpClient设置BaseAddress,这样组件中无需修改调用代码:

// Program.cs
builder.Services.AddHttpClient(client =>
{
    client.BaseAddress = new Uri(builder.HostEnvironment.BaseAddress);
});

组件中保持原相对路径调用即可:

@inject HttpClient Http

protected override async Task OnInitializedAsync()
{
    var result = await Http.GetFromJsonAsync<List<Product>>("api/Product");
    if (result != null)
    {
        Products = result;
    }
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.28 20:55:38