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

ASP.NET MVC Identity授权配置异常:注册页无法匿名访问且报404

问题原因及解决方法

核心问题

你配置匿名访问页面时未指定Identity区域(Area),导致框架无法匹配到Identity下的Register和Login页面,触发授权拦截后重定向到了不存在的非Area路径Account/Login,从而出现404错误。

修正后的代码

builder.Services.AddAuthorization(options =>
{
    options.AddPolicy("Admin", p => p.RequireRole(Roles.Administrator));
    options.AddPolicy("Employee", p => p.RequireRole(Roles.Employee));
});

builder.Services.AddRazorPages(options =>
{
    // 对Identity区域下所有内容应用Admin授权策略
    options.Conventions.AuthorizeAreaFolder("Identity", "/", "Admin");

    // 为Identity区域内的指定页面开启匿名访问
    options.Conventions.AllowAnonymousToAreaPage("Identity", "/Account/Register");
    options.Conventions.AllowAnonymousToAreaPage("Identity", "/Account/Login");
});

关键说明

  • 必须使用AllowAnonymousToAreaPage而非AllowAnonymousToPage,明确指定页面所属的Area为Identity,同时路径要对应Identity页面的实际位置(默认是/Account/Register和/Account/Login)。
  • 原代码里的AllowAnonymousToPage("/Register")会匹配根目录下的Register页面,而非Identity区域内的页面,所以授权规则依然会拦截Identity的Register请求,导致错误跳转。

额外验证点

  1. 确认Identity页面结构为Areas/Identity/Pages/Account/Register.cshtml和Areas/Identity/Pages/Account/Login.cshtml,若路径不同需同步调整代码中的页面路径参数。
  2. 检查是否有其他全局授权规则或中间件覆盖了当前配置。

内容的提问来源于stack exchange,提问作者Modestas Vacerskas

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.22 05:34:57