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

如何用Register.razor覆盖Identity Core的Register.cshtml页面?

解决Blazor Server自定义Register页面优先于Identity MVC页面的问题

核心原因

ASP.NET Core默认路由优先级中,MVC Razor页面的匹配优先级高于Blazor组件路由,所以即使你定义了同URL的Blazor页面,仍会优先加载Identity DLL里的MVC页面。

具体解决方法

方法1:调整路由注册顺序

在Program.cs里把Blazor相关的路由注册代码放在Identity路由之前,让Blazor组件先匹配请求:

// 先注册Blazor路由
app.MapBlazorHub();
app.MapFallbackToPage("/_Host");

// 再注册Identity的Razor Pages路由
app.MapRazorPages();

默认项目里MapRazorPages()通常在Blazor路由之前,调整顺序后Blazor组件的路由会先被匹配。

方法2:移除Identity MVC页面的路由规则

通过自定义路由约定,清除Identity DLL中Register页面的路由模板,让Blazor页面的路由生效:

builder.Services.AddRazorPages(options =>
{
    options.Conventions.Add(new RemoveIdentityRegisterRouteConvention());
});

// 自定义路由约定类
public class RemoveIdentityRegisterRouteConvention : IPageRouteModelConvention
{
    public void Apply(PageRouteModel model)
    {
        // 定位到Identity里的Register页面
        if (model.RelativePath.Equals("/Identity/Account/Register.cshtml", StringComparison.OrdinalIgnoreCase))
        {
            // 移除该页面的所有路由匹配规则
            model.Selectors.Clear();
        }
    }
}

方法3:用MapWhen拦截特定路由

直接针对/Identity/Account/Register路径,让它走Blazor的路由管道:

app.MapRazorPages();

// 拦截Register路径,优先使用Blazor路由
app.MapWhen(context => 
    context.Request.Path.StartsWithSegments("/Identity/Account/Register"), 
    appBuilder =>
{
    appBuilder.UseRouting();
    appBuilder.UseEndpoints(endpoints =>
    {
        endpoints.MapBlazorHub();
        endpoints.MapFallbackToPage("/_Host");
    });
});

验证方式

修改后重启应用,访问目标URL,可在自定义Register.razor里加个独特的标识(比如专属标题或组件),确认是否加载的是你的Blazor页面。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.25 01:20:05