2014-02-08 16 views
1

我已經編寫了一個自定義篩選器屬性來檢查每個控制器的動作,如果用戶有權訪問該操作,我給予訪問,否則我重定向到控制器未經授權的訪問,這裏是我的代碼:通過檢查訪問權隱藏ActionLinks的通用方法

public class AuthorizationAttribute : ActionFilterAttribute 
{ 
    public override void OnActionExecuting(ActionExecutingContext filterContext) 
    { 
     string actionName = filterContext.ActionDescriptor.ActionName; 
     string controllerName = filterContext.ActionDescriptor.ControllerDescriptor.ControllerName; 

     if (!CheckAccessRight(actionName, controllerName)) 
     { 
      string redirectUrl = string.Format("?returnUrl={0}", filterContext.HttpContext.Request.Url.PathAndQuery); 

      filterContext.HttpContext.Response.Redirect(FormsAuthentication.LoginUrl + redirectUrl, true); 
     } 
     else 
     { 
      base.OnActionExecuting(filterContext); 
     } 
    } 
} 

這裏是我的CheckAccessRight方法:

private bool CheckAccessRight(string Action, string Controller) 
{ 
    if (HttpContext.Current.Session["userId"] != null) 
    { 
     string userID = HttpContext.Current.Session["userId"].ToString(); 
     using (var db = new cloud_clinicEntities()) 
     { 
      assignment objAss = db.assignments.SingleOrDefault(model => model.userid == userID); 

      String UserRole = objAss.itemname; 

      itemchildren objChild = db.itemchildrens.SingleOrDefault(model => model.parent == UserRole && model.child == Controller + " " + Action); 

      if (objChild != null) 
      { 
       return true; 
      } 
      else 
      { 
       return false; 
      } 
     } 
    } 
    else 
    { 
     return false; 
    } 
} 

現在我想對我的每一個觀點,如果有操作鏈接到用戶無權訪問它不應該被網頁上呈現的控制器操作或者它應該被隱藏。如何以通用的方式做到這一點,我有想法,我可以通過在每個操作鏈接上添加if語句來實現,但我不認爲它是更好的方法。

+0

的[基於角色的內容asp.net的MVC(http://stackoverflow.com/questions/928654/role-based-content-asp-net-mvc) –

回答

0

創建一個HTML Helper,這是對普通ActionLink的擴展,但它需要一個更多的參數,它是Role String,如下所示。 Credit goes to Eu-ge-ne for his original solution

public static class Html 
{ 
    public static string RoleActionLink(this HtmlHelper html, string role, string linkText, string actionName, string controllerName) 
    { 
     return html.ViewContext.HttpContext.User.IsInRole(role) 
      ? html.ActionLink(linkText, actionName, controllerName) 
      : String.Empty; 
    } 
} 
+0

可能重複的,但怎麼樣,如果我有這樣的一些錨標籤: Link 我該如何處理呢? –

+0

@EhsanSajjad您的頁面上有多少個錨鏈接,如果您正在專門爲菜單進行交談,那麼您可以在MVC中擁有安全修剪菜單。但是,如果您在整個頁面上討論隨機鏈接,恐怕您必須使用自定義助手或條件。如果此要求是顯示/隱藏表格數據上的某些鏈接,那麼我會簡單地使用Html Helper,因爲它很容易維護。 – ramiramilu

+0

你可以分享一些示例代碼,我需要隱藏我的網頁上的一些隨機鏈接,我寫了自定義操作過濾器和用戶是能夠查看頁面,但要求是隱藏它,以及如果它不在其權利 –