Blazor路由正则表达式报错求助:升级Web App后约束解析失败
问题背景
原Blazor WebAssembly项目按文档升级为.NET 8 Blazor Web App后,正则路由无法正常工作,但直接用Blazor Web App模板创建的项目中该正则路由可正常运行。
错误信息
Unhandled exception rendering component: The constraint entry 'doc' - 'regex((.)(?:/details)$)' on the route '/{{doc:regex((.)(?:/details)$)}' could not be resolved by the constraint resolver of type 'DefaultInlineConstraintResolver'.
System.InvalidOperationException: The constraint entry 'doc' - 'regex((.)(?:/details)$)' on the route '/{{doc:regex((.)(?:/details)$)})}' could not be resolved by the constraint resolver of type 'DefaultInlineConstraintResolver'.
当前路由代码
@attribute [Route(@"/{*doc:regex((.*)(?:\/details)$)}")] @rendermode InteractiveWebAssembly [Parameter] public string doc { get; set; }
(注:原代码存在多余括号、引号的语法错误,已修正基础格式)
当前Program.cs代码
var builder = WebApplication.CreateBuilder(args); builder.Services.AddRazorComponents() .AddInteractiveWebAssemblyComponents(); builder.Services.AddControllers(); var app = builder.Build(); if (app.Environment.IsDevelopment()) { app.UseWebAssemblyDebugging(); } else { app.UseExceptionHandler("/Error"); app.UseHsts(); } app.UseHttpsRedirection(); app.UseStaticFiles(); app.UseAntiforgery(); app.MapRazorComponents<App>() .AddInteractiveWebAssemblyRenderMode() .AddAdditionalAssemblies(typeof(Client._Imports).Assembly); app.MapControllers(); app.Run();
问题排查与解决方案
1. 修正路由语法错误
原路由代码存在两处语法问题:
- 错误使用双大括号
{{,正确应为单大括号{ - 末尾多余的冗余符号,修正后的正确路由模板如下:
@attribute [Route("/{*doc:regex((.*)(?:/details)$)}")]
2. 手动注册正则路由约束
Blazor Web App模板项目默认已配置正则约束,但升级后的项目遗漏了该注册步骤。在Program.cs中添加正则约束的映射:
builder.Services.AddRouting(options => { options.ConstraintMap["regex"] = typeof(Microsoft.AspNetCore.Routing.RegexRouteConstraint); });
修改后的完整Program.cs代码:
var builder = WebApplication.CreateBuilder(args); // 注册正则路由约束 builder.Services.AddRouting(options => { options.ConstraintMap["regex"] = typeof(Microsoft.AspNetCore.Routing.RegexRouteConstraint); }); builder.Services.AddRazorComponents() .AddInteractiveWebAssemblyComponents(); builder.Services.AddControllers(); var app = builder.Build(); if (app.Environment.IsDevelopment()) { app.UseWebAssemblyDebugging(); } else { app.UseExceptionHandler("/Error"); app.UseHsts(); } app.UseHttpsRedirection(); app.UseStaticFiles(); app.UseAntiforgery(); app.MapRazorComponents<App>() .AddInteractiveWebAssemblyRenderMode() .AddAdditionalAssemblies(typeof(Client._Imports).Assembly); app.MapControllers(); app.Run();
3. 验证正则表达式逻辑
当前正则(.*)(?:\/details)$用于匹配以/details结尾的路径,若实际业务需要调整匹配规则,可直接修改正则表达式内容。
内容的提问来源于stack exchange,提问作者Артём Цибульский

