在Blazor Server应用中托管Web API遭遇404错误的排查求助
解决Blazor Server中Web API接口404的问题
从你的代码来看,导致http://localhost:5000/stripe/customerwebhook返回404的核心原因是路由配置冲突,再结合路由匹配细节问题,下面一步步拆解修复方案:
1. 修复Startup中的路由冲突问题
你在ConfigureServices里设置了options.EnableEndpointRouting = false,这会直接禁用ASP.NET Core的端点路由系统,但又在Configure方法里同时使用了app.UseMvcWithDefaultRoute()和app.UseEndpoints(...)——这两者是互斥的,会导致API控制器的路由无法被正确识别和映射。
具体修复步骤:
- 删除
services.AddMvc(options => options.EnableEndpointRouting = false).SetCompatibilityVersion(CompatibilityVersion.Version_3_0);这一行,改用支持端点路由的API控制器配置。 - 调整
Configure方法中的中间件顺序,移除冲突的UseMvcWithDefaultRoute,保留端点路由配置。
修改后的ConfigureServices片段:
public void ConfigureServices(IServiceCollection services) { OnConfiguringServices(services); services.AddHttpContextAccessor(); services.AddScoped<HttpClient>(serviceProvider => { var uriHelper = serviceProvider.GetRequiredService<NavigationManager>(); return new HttpClient { BaseAddress = new Uri(uriHelper.BaseUri) }; }); services.AddHttpClient(); services.AddAuthentication(); services.AddAuthorization(); // 替换原AddMvc配置,使用专门针对API控制器的AddControllers services.AddControllers(); services.AddControllersWithViews(); services.AddRazorPages(); services.AddServerSideBlazor().AddHubOptions(o => { o.MaximumReceiveMessageSize = 10 * 1024 * 1024; }); }
修改后的Configure方法片段:
public void Configure(IApplicationBuilder app, IWebHostEnvironment env, ApplicationIdentityDbContext identityDbContext) { OnConfiguring(app, env); if (env.IsDevelopment()) { Microsoft.IdentityModel.Logging.IdentityModelEventSource.ShowPII = true; app.UseDeveloperExceptionPage(); } else { app.Use((ctx, next) => { return next(); }); } app.UseHttpsRedirection(); app.UseStaticFiles(); app.UseCookiePolicy(); app.UseRouting(); app.UseAuthentication(); app.UseAuthorization(); // 移除UseMvcWithDefaultRoute,统一使用端点路由 app.UseEndpoints(endpoints => { endpoints.MapControllerRoute( name: "default", pattern: "{controller=Home}/{action=Index}/{id?}"); // 确保MapControllers被正确添加,这会自动映射所有带[ApiController]和[Route]的API控制器 endpoints.MapControllers(); endpoints.MapBlazorHub(); endpoints.MapFallbackToPage("/_Host"); }); }
2. 确认API接口的路由路径
你的CustomerWebhookController上的路由属性是[Route("stripe/[controller]")],ASP.NET Core会自动移除控制器名称的Controller后缀,所以生成的路由路径是/stripe/CustomerWebhook。
虽然路由默认不区分大小写,但要注意:
- 你的接口只定义了
[HttpPost],如果用GET请求访问会直接返回404,必须用POST请求测试。 - 如果希望路径严格是
/stripe/customerwebhook(全小写),可以手动指定路由,不依赖[controller]占位符:
[Route("stripe/customerwebhook")] [ApiController] public class CustomerWebhookController : ControllerBase { [HttpPost] public async Task<IActionResult> Index() { return Ok(); } }
3. 额外检查点
- 确认项目启动端口确实是5000,可以查看
launchSettings.json中的端口配置。 - 检查是否有自定义中间件拦截了请求,导致API接口无法被正常访问。
内容的提问来源于stack exchange,提问作者Ajit Goel




