2011-09-07 65 views
2

我有這樣的自定義授權類來檢查,如果用戶是管理員:處理使用自定義未授權的屬性

public class IsAdminAttribute : AuthorizeAttribute 
    { 
     private datacontext() db = new datacontext(); 
     protected override bool AuthorizeCore(HttpContextBase httpContext) 
     { 
      var isAuthorized = base.AuthorizeCore(httpContext); 
      if (isAuthorized) 
      { 
       var currentUser = httpContext.User.Identity.Name; 
       return db.Users.Where(u => u.UserName == currentUser).Where(ut => ut.UserTypeID == 2).Count() == 1 ? true : false; 
      } 
      return isAuthorized; 
     } 

    } 

,並用在這裏:

[IsAdmin] 
public ActionResult CreateUser() 
{ 
    ViewBag.UserTypeID = new SelectList(db.UserTypes, "UserTypeId", "Name"); 
    return View(); 
} 

和工作正常,但需要我當用戶未被授權時返回到我的登錄頁面。我想要發生的事情是用戶被重定向到某處,並彈出錯誤消息。我如何處理拒絕訪問事件?

回答

7

如何處理拒絕訪問事件?

只需重寫HandleUnauthorizedRequest方法和直接返回你喜歡的觀點:

protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext) 
{ 
    filterContext.Result = new ViewResult 
    { 
     ViewName = "Unauthorized" 
    }; 
} 

,這會使得~/Views/Shared/Unauthorized.cshtml。您也可以將視圖模型,母版頁等傳遞給ViewResult

+0

不錯。謝謝Darin。 – Ron