Asp.net-Mvc
將 MVC 中的未授權頁面訪問重定向到自定義視圖
我有一個 MVC 網站,其中訪問基於各種角色。一旦使用者登錄到系統,他們就可以看到導航到他們被授權的頁面。但是,一些使用者可能仍會嘗試使用直接 URL 訪問頁面。如果他們這樣做,系統會自動將他們重定向到登錄頁面。而不是登錄頁面,我想將它們重定向到另一個視圖(未經授權)。
Web.Config 具有以下條目:
<customErrors mode="On"> <error statusCode="401" redirect="~/Home/Unauthorized" /> <error statusCode="404" redirect="~/Home/PageNotFound" /> </customErrors> <authentication mode="Forms"> <forms name="Development" loginUrl="~/Account/Login" cookieless="UseCookies" timeout="120"></forms> </authentication>我也在 Global.asax.cs 中註冊了這些路線。
routes.MapRoute( name: "Unauthorized", url: "{controller}/{action}/{id}", defaults: new { controller = "Home", action = "Unauthorized", id = UrlParameter.Optional } ); routes.MapRoute( name: "PageNotFound", url: "{controller}/{action}/{id}", defaults: new { controller = "Home", action = "PageNotFound", id = UrlParameter.Optional } );會足夠嗎?
通過以下更改,它正在工作
public class CustomAuthorize : AuthorizeAttribute { protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext) { //filterContext.Result = new HttpUnauthorizedResult(); // Try this but i'm not sure filterContext.Result = new RedirectResult("~/Home/Unauthorized"); } public override void OnAuthorization(AuthorizationContext filterContext) { if (this.AuthorizeCore(filterContext.HttpContext)) { base.OnAuthorization(filterContext); } else { this.HandleUnauthorizedRequest(filterContext); } } }然後在Controller或Action上應用如下:
[CustomAuthorize(Roles = "Admin")]使用上述方法,我需要重新訪問所有控制器/操作並更改 Authorized 屬性!還需要進行一些測試。
我仍然不確定為什麼在 MVC 文件中解釋了 Web.Config 路由不能正常工作。可能在 MVC 4 中發生了一些變化!
經過一番研究,我認為這個問題最簡單的答案就是創建自定義授權,這與 jbbi 的授權非常相似(但由於“new HttpUnauthorizedResult()”在內部自動重定向到登錄名,所以該授權不起作用 - 至少在具有身份的 mvc 5 中)
public class CustomAuthorize : AuthorizeAttribute { protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext) { if (!filterContext.HttpContext.User.Identity.IsAuthenticated) { //if not logged, it will work as normal Authorize and redirect to the Login base.HandleUnauthorizedRequest(filterContext); } else { //logged and wihout the role to access it - redirect to the custom controller action filterContext.Result = new RedirectToRouteResult(new RouteValueDictionary(new { controller = "Error", action = "AccessDenied" })); } } }並且用法和預設的Authorize一樣:
[CustomAuthorize(Roles = "Administrator")]然後,只是為了做正確的事情,不要忘記將錯誤頁面的Http程式碼發送出去。例如在控制器中是這樣的。
public ActionResult AccessDenied() { Response.StatusCode = 403; return View(); }這很容易,它可以工作,甚至我(.net mvc 新手)也理解這一點。
**注意:**它與 401 程式碼不同 - 它總是會接管 401 並在內部將其重定向到登錄。但就我而言,根據定義,403 也很合適。