我只希望管理員可以訪問此控制器及其操作,因此我撰寫了以下代碼:
[Authorize(Roles = Helper.AdminRole)]
public class AdminController : Controller
{
public IActionResult AdminPanel()
{
return View();
}
//other actions only available to admins
}
如果用戶未登錄并且他不在指定的角色中,我會在 URL 中看到 404 Not Found 頁面:
..../AccessDenied?ReturnUrl=/Admin/AdminPanel
在這種情況下,我如何制作自定義錯誤頁面,其中要求用戶登錄以便他可以確認他的角色,并且當他成功登錄并且他處于正確的角色以被重定向到他想去的地方時,但如果他的角色無效,無法重定向到其他地方/顯示自定義錯誤頁面?
uj5u.com熱心網友回復:
您的錯誤是由于缺少登錄路徑設定引起的,不是錯誤的角色或密碼。(所以錯誤代碼是 404 而不是 401)
你可以看到測驗結果:
如果你想自定義錯誤頁面,你可以閱讀官方檔案:

uj5u.com熱心網友回復:
以cookie認證為例,你只需要在program.cs(.Net 6)中這樣配置:
builder.Services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
.AddCookie(x =>
{
//When user doesn't login and he access to an action with [Authorize],
//He will redirect to the loginPath
x.LoginPath = "/{controller}/{action}";
//When user has loged in but the role is not the specified role,
//He will redicet to the AccessDeniedPath,
//Then you can custom your own error page in this path.
x.AccessDeniedPath = "/{controller}/{action}";
});
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/454521.html
下一篇:Tabview滾動行為
