Blazor SSR带参数路由如何排除ads.txt文件访问?
解决Blazor SSR中ads.txt被路由拦截的问题
问题根源
你的Blazor SSR路由domainname/{urlparam}会匹配根路径下所有请求,包括/ads.txt,导致静态文件无法被正确加载。之前尝试的UseWhen方案因中间件顺序错误和重复路由映射,引发了EndpointRoutingMiddleware相关异常。
正确解决方案
步骤1:放置ads.txt到正确目录
将ads.txt文件放到项目的wwwroot文件夹中,这是ASP.NET Core静态文件的默认读取目录。
步骤2:调整Program.cs的路由配置
以下两种方案任选其一即可:
方案A:使用MapWhen过滤请求
通过MapWhen仅对非/ads.txt的请求映射Blazor组件,同时确保静态文件中间件优先处理请求:
var builder = WebApplication.CreateBuilder(args); // 服务注册保持不变 builder.Services.AddRazorComponents() .AddInteractiveServerComponents() .AddInteractiveWebAssemblyComponents(); var connectionString = builder.Configuration.GetConnectionString("DefaultConnection") ?? throw new InvalidOperationException("Connection string 'DefaultConnection' not found."); builder.Services.AddDbContext<ApplicationDbContext>(options => options.UseSqlServer(connectionString)); builder.Services.AddHttpClient(); var app = builder.Build(); // 环境配置保持不变 if (app.Environment.IsDevelopment()) { app.UseWebAssemblyDebugging(); } else { app.UseExceptionHandler("/Error", createScopeForErrors: true); app.UseHsts(); } app.UseHttpsRedirection(); app.UseStaticFiles(); // 优先处理静态文件,包括ads.txt app.UseAntiforgery(); // 仅对非ads.txt的请求映射Blazor组件 app.MapWhen(context => !context.Request.Path.Equals("/ads.txt"), appBuilder => { appBuilder.MapRazorComponents<App>() .AddInteractiveServerRenderMode() .AddInteractiveWebAssemblyRenderMode() .AddAdditionalAssemblies(typeof(TestProject.Client._Imports).Assembly); }); app.Run();
方案B:给路由添加正则约束
直接给Blazor路由添加正则约束,排除ads.txt作为urlparam的情况:
var builder = WebApplication.CreateBuilder(args); // 服务注册保持不变 builder.Services.AddRazorComponents() .AddInteractiveServerComponents() .AddInteractiveWebAssemblyComponents(); var connectionString = builder.Configuration.GetConnectionString("DefaultConnection") ?? throw new InvalidOperationException("Connection string 'DefaultConnection' not found."); builder.Services.AddDbContext<ApplicationDbContext>(options => options.UseSqlServer(connectionString)); builder.Services.AddHttpClient(); var app = builder.Build(); // 环境配置保持不变 if (app.Environment.IsDevelopment()) { app.UseWebAssemblyDebugging(); } else { app.UseExceptionHandler("/Error", createScopeForErrors: true); app.UseHsts(); } app.UseHttpsRedirection(); app.UseStaticFiles(); // 优先处理静态文件 app.UseAntiforgery(); // 添加路由约束,排除ads.txt app.MapRazorComponents<App>() .AddInteractiveServerRenderMode() .AddInteractiveWebAssemblyRenderMode() .AddAdditionalAssemblies(typeof(TestProject.Client._Imports).Assembly) .AddRouteConstraint("{urlparam:regex(^(?!ads\\.txt$).*)}"); app.Run();
错误原因说明
你之前的代码存在两个核心问题:
- 重复调用
MapRazorComponents<App>(),导致路由中间件冲突 - 使用
UseWhen嵌套UseEndpoints的方式不符合.NET 6+ WebApplication模型的中间件顺序规则,引发了EndpointRoutingMiddleware的顺序异常
上述两种方案都移除了重复映射,同时确保静态文件中间件优先处理/ads.txt请求,避免被Blazor路由拦截。
内容的提问来源于stack exchange,提问作者dnky
相关产品推荐
相关产品推荐

