2011-09-16 28 views
18

我正在使用MVC 3與窗體身份驗證。在我的控制器或方法,我做了以下內容:ASP.NET - 重定向到錯誤頁面,如果角色授權失敗

[Authorize (Roles = "developer")] 

在這種情況下,我要檢查,如果用戶在如果沒有記錄,他們返回到登錄頁面。但是,如果該用戶的'IsInRole'檢查返回false,我希望他們轉到另一個視圖,上面寫着'未經授權'。

什麼是最好的方式來完成這樣的事情?我希望避免創建一個新的授權屬性,所以我不必在整個應用程序中重構每個授權屬性,但是如果這是必需的,我會走這條路線。

回答

44

自定義授權屬性重寫HandleUnauthorizedRequest方法可以做的工作:

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() 
{ 
    ... 
} 
+0

這工作完美。 – Brandon

+0

完美...謝謝... – Shaz

+3

你在哪裏把這個自定義實現? –

1

您也可以與401個狀態碼自定義錯誤頁做到這一點。

查看this question獲取實施細節。

0

你可以像這樣使用它。因爲如果你沒有權威,它來的方法。 授權控制不是必需的

protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext) 
    { 
     if (!filterContext.HttpContext.User.Identity.IsAuthenticated) 
     { 
      // The user is not authenticated 
      base.HandleUnauthorizedRequest(filterContext); 
     } 
     else 
     { 
      filterContext.Result = new ViewResult 
      { 
       ViewName = "~/Views/Shared/Unauthorized.cshtml", 
      }; 
     } 
    } 
相關問題