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开销。
修复方案
- 删掉Web API Startup中如下两行注册代码:
services.AddScoped<IReporterRepository, ReporterRepository>(); services.AddHttpClient<IReporterRepository, ReporterRepository>(client => { client.BaseAddress = new Uri("https://localhost:5011/"); });
- 改写
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); } }
- 保留
IReporterRepository和ReporterRepository在Blazor WebAssembly项目中的注册和使用,让前端通过这个封装类调用上述修复后的API接口拿数据即可。
内容的提问来源于stack exchange,提问作者MarkCo
相关产品推荐
相关产品推荐

