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

Blazor WebAssembly调用ASP.NET Core Web API出现HttpClient 100秒超时错误

问题根因

你遇到的超时错误本质是代码逻辑写反导致的无限请求死循环+依赖注入误用,核心问题如下:

  • 类的使用场景完全错位:ReporterRepository 是Blazor WebAssembly前端项目专用的封装类,设计目的是让前端侧通过HTTP请求调用后端Web API接口获取报表数据,你现在把它直接注册到后端Web API的服务容器中,还让API控制器调用它,完全违背了该类的设计用途。
  • 触发了无限请求死循环:你在Web API的Startup中给ReporterRepository注入的HttpClient BaseAddress设置为Web API自身的地址https://localhost:5011/,当API控制器调用_repo.GetAll()时,相当于Web API自己给自己发HTTP请求:

    调用链路:Postman请求/api/WebReport/GatherAllReports → 控制器调用_repo.GetAll() → GetAll()内部发HTTP请求到Web API自身的/ReportsPage/GatherAllReports路径
    如果该路径不存在,请求会一直挂起直到超时;如果该路径对应的接口也会调用ReporterRepository,就会形成无限递归的HTTP调用,所有请求都被阻塞,最终触发100秒超时的TaskCanceledException。

  • 逻辑冗余:后端Web API本身就可以直接通过注入的ReportContext读取数据库数据,完全不需要绕一层HTTP请求自己调用自己,你相当于把前端的调用逻辑硬搬到了后端,平白多了完全多余的HTTP开销。
修复方案
  1. 删掉Web API Startup中如下两行注册代码:
services.AddScoped<IReporterRepository, ReporterRepository>();
services.AddHttpClient<IReporterRepository, ReporterRepository>(client =>
    {
        client.BaseAddress = new Uri("https://localhost:5011/");
    });
  1. 改写WebReportController的逻辑,直接通过DbContext读取数据,不要调用前端专用的ReporterRepository:
[Route("api/[controller]")]
[ApiController]
public class WebReportController : ControllerBase
{
    // 直接注入数据库上下文
    private readonly ReportContext _context;

    public WebReportController (ReportContext context)
    {
        _context = context;
    }

    [HttpGet]
    [Route("GatherAllReports")]
    public async Task<IActionResult> Get()
    {
        // 直接读库返回数据即可
        var reportValues = await _context.Reports.ToListAsync();
        return Ok(reportValues);
    }
}
  1. 保留IReporterRepository和ReporterRepository在Blazor WebAssembly项目中的注册和使用,让前端通过这个封装类调用上述修复后的API接口拿数据即可。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.01 19:24:05