2013-10-14 222 views
1

任何人都可以告訴我如何在mvc3中爲所有操作方法實現基於角色的授權。現在在我的應用程序中,我沒有編寫任何代碼來跟蹤用戶角色。在mvc3中基於角色的授權

只有在應用程序的主菜單中,我檢查了構建菜單的角色,但是當我鍵入url時,我不想拒絕用戶訪問。我正在考慮實現屬性。任何人都可以給我建議。

在此先感謝

+0

在OnAuthorization授權過濾器中寫入您的邏輯並放入基本控制器並將該基本控制器繼承到每個控制器。 –

回答

0

嘗試下面的內容。

protected override void OnAuthorization(AuthorizationContext filter_context) 
{ 
    #region If auth cookie is present 
    if (auth_cookie != null) 
    { 
     #region IF loggedin user is a member 
     if (SiteUsers.LoggedInUser.UserRole == UserRole.Buyer 
      && filter_context.ActionDescriptor.ControllerDescriptor.ControllerName == "Home" 
      && filter_context.ActionDescriptor.ActionName == "Index") 
     { 
      filter_context.Result = RedirectToAction("Index", "Home"); 
     } 
     #endregion 

     #region If loggedin user is a super admin 
     else if (SiteUsers.LoggedInUser.UserRole == UserRole.Administrator && !filter_context.ActionDescriptor.ControllerDescriptor.GetCustomAttributes(typeof(Adminstrator), false).Any()) 
     { 
      if (!filter_context.ActionDescriptor.GetCustomAttributes(typeof(AllowAdmin), false).Any()) 
      { 
       filter_context.Result = RedirectToAction("Home", "Admin"); 
      } 

     } 
     #endregion 

     ViewBag.SiteUsers = SiteUsers; 
    } 
    #endregion 

    #region if authorization cookie is not present and the action method being called is not marked with the [SkipAuthentication] attribute 
    else if (!filter_context.ActionDescriptor.GetCustomAttributes(typeof(SkipAuthentication), false).Any()) 
    { 
     if (Request.IsAjaxRequest()) filter_context.Result = Json(new ActionOutput { Results = new List<string> { Url.Action("Signin", "Home") }, Status = ActionStatus.Error }, JsonRequestBehavior.AllowGet); 
     else 
      filter_context.Result = RedirectToAction("Signin", "Home"); 
    } 
    #endregion 

    #region if authorization cookie is not present and the action method being called is marked with the [SkipAuthentication] attribute 
    else 
    { 
     SiteUsers = new ReplictivityUserDetails(); 
     ViewBag.SiteUsers = SiteUsers; 
    } 
    #endregion 
}