2013-07-02 140 views
1

我需要[授權]像ASP.Net mvc 3/4自定義屬性。像下面的東西。「授權」像自定義屬性在ASP.Net MVC 3

[AdminOnly] 
public ActionResult OpenAddListUser() 
{ 
    //Do some actions 
} 

這裏[AdminOnly]將檢查一些用戶crediantials。我所需要的只是如果AdminOnly無效,然後返回一些ActionResult View或者重定向到其他一些視圖,如登錄。

回答

3
public class AdminOnly : AuthorizeAttribute 
    { 

     protected override bool AuthorizeCore(HttpContextBase httpContext) 
     { 
      bool baseAuthorized = base.AuthorizeCore(httpContext); 
      if (!baseAuthorized) { 
        return false; 
      } 
      //here should be your admin checking logic 
      bool isAdmin = YourLogic.IsAdmin(httpContext.User.Identity.Name); 
      return isAdmin; 
     } 

    } 
}