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

ASP.NET Core Identity自定义Access Denied页面路径配置疑问

问题原因

你配置的AddCookie是针对CookieAuthenticationDefaults.AuthenticationScheme这个认证方案的,但Microsoft.AspNetCore.Identity.UI 8.0.0默认使用的是IdentityConstants.ApplicationScheme作为认证方案,所以你单独添加的Cookie配置根本没被Identity的授权逻辑用到,系统还是走了Identity内置的默认AccessDenied路径。

解决方案

不需要单独调用AddCookie,直接修改Identity自带的Application Cookie配置即可,用ConfigureApplicationCookie方法覆盖默认设置:

示例代码

如果你的项目用的是AddDefaultIdentity:

builder.Services.AddDefaultIdentity<IdentityUser>(options => options.SignIn.RequireConfirmedAccount = true)
    .AddEntityFrameworkStores<ApplicationDbContext>()
    .AddDefaultUI();

// 配置Identity的Application Cookie选项
builder.Services.ConfigureApplicationCookie(options =>
{
    options.LoginPath = "/account/login";
    options.LogoutPath = "/account/logout";
    options.AccessDeniedPath = "/account/AccessDenied";
});

如果是用AddIdentity(支持角色管理):

builder.Services.AddIdentity<IdentityUser, IdentityRole>()
    .AddEntityFrameworkStores<ApplicationDbContext>()
    .AddDefaultUI()
    .AddDefaultTokenProviders();

// 配置Identity的Application Cookie选项
builder.Services.ConfigureApplicationCookie(options =>
{
    options.LoginPath = "/account/login";
    options.LogoutPath = "/account/logout";
    options.AccessDeniedPath = "/account/AccessDenied";
});

额外注意

确保你已经创建了对应的AccountController和AccessDenied视图,路由能正确匹配/account/AccessDenied。比如控制器里需要包含:

public IActionResult AccessDenied()
{
    return View();
}

内容的提问来源于stack exchange,提问作者Oleg Sh

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.02 22:18:21