c# – ASP.NET – 如果角色授權失敗,重定向到錯誤頁面
我使用MVC 3與表單身份驗證.在我的控制器或方法上,我正在做以下操作:
[Authorize (Roles = "developer")]
在這種情況下,我想檢查使用者是否登入,否則返回到登入頁面.但是,如果該使用者的“IsInRole”檢查返回false,我希望他們去一個不同的檢視,例如“未授權”.
什麼是最好的方式來完成這樣的事情?我希望避免建立一個新的授權屬性,所以我沒有必要重構整個應用程式中的每個Authorize屬性,但如果這是所需的,我將去那條路線.
方法的自定義授權屬性可以執行以下任務:
public class MyAuthorizeAttribute : AuthorizeAttribute { protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext) { if (!filterContext.HttpContext.User.Identity.IsAuthenticated) { // The user is not authenticated base.HandleUnauthorizedRequest(filterContext); } else if (!this.Roles.Split(',').Any(filterContext.HttpContext.User.IsInRole)) { // The user is not in any of the listed roles => // show the unauthorized view filterContext.Result = new ViewResult { ViewName = "~/Views/Shared/Unauthorized.cshtml" }; } else { base.HandleUnauthorizedRequest(filterContext); } } }
接著:
[MyAuthorize(Roles = "developer")] public ActionResult Develop() { ... }
程式碼日誌版權宣告:
翻譯自:http://stackoverflow.com/questions/7447705/asp-net-redirect-to-error-page-if-roles-authorization-fails