2012-03-26 102 views
0

我想基于用户权限使用自定义安全框架禁用/启用控件。我试图在代码隐藏文件中使用此代码MVC3访问控制

protected void OnLoadComplete(object sender, EventArgs e) 
     { 
      if ((ViewData[Constants.Permission]).Equals(Security.UserAccess.ReadOnlyAccess)) 
      { 
       foreach (var control in this.Page.Controls ) 
       { 
        control.IsReadOnly = true; 
       } 
      } 
     } 

但是,控件的IsReadOnly属性不可用。有没有办法可以解决这个问题或更好的方法来实现这一目标?

---更新---

Controller.cs

[Proxy.AimsAccessLevel] 
    public ActionResult Edit(int clientId) 
    { 
     ClientId = clientId; 
     //SetClientDetails(); 

     var Selection = new SelectionArgs(clientId, null); 

     if (Selection.SelectionFlag == null || Selection.SelectionFlag == "N") 
      Selection.EffectiveDate = new DateTime(DateTime.Now.Year + 1, 1, 1); 

     return View(Selection); 
    } 

proxy.cs

public class AccessLevel : AuthorizeAttribute 
     { 
      protected override bool AuthorizeCore(HttpContextBase httpContext) 
      { 
       Roles = Constants.AccessLevel.FullEdit + Constants.AccessLevel.ReadOnly.ToString() + 
         Constants.AccessLevel.RestrictedEdit; 
       return base.AuthorizeCore(httpContext); 
      } 
     } 
+2

MVC没有一个代码隐藏。你使用MVC还是WebForms? – 2012-03-26 15:01:38

+0

即时通讯使用mvc我使用<%@ Page CodeBehind =“Edit.aspx.cs”Title =“”Language =“C#”MasterPageFile =“〜/ Views/Shared/Site.Master”Inherits =“Views.Selection.Edit” %> 给了我没有错误 – 2012-03-26 15:08:15

回答

4

你不应该使用代码隐藏与ASP.Net MVC - 它去违反MVC的原则。视图不应该是决定用户是否拥有权限的事情。确定页面是否可见属于控制器级别。

处理权限的更好方法是在控制器上使用[Authorize]属性。即,

public MyController : Controller 
{ 
    [Authorize(Roles = "admin")] // Uses default FormsAuthentication 
    public ActionResult Index() 
    { 
     // ... 
    } 
} 

您可以编写自己的Authorize属性绑定到您的自定义框架:

[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method)] 
public class MyAuthorizeAttribute : AuthorizeAttribute 
{ 
    public override void OnAuthorization(AuthorizationContext filterContext) 
    { 
     // ... authorization stuff here ... 
    } 
} 

然后用它在你的控制器动作:

public HomeController : Controller 
{ 
    [MyAuthorize] 
    public ActionResult Index() 
    { 
     // ... 
    } 
} 
+0

我会将这个覆盖添加到控制器? – 2012-03-26 15:16:22

+0

(修正了一些格式)。不,重写不在控制器中 - 这是自定义属性的一部分。该属性然后发送到控制器上,或者您想要限制的控制器动作。 – Leniency 2012-03-26 15:22:36

+0

我无法访问该框架的源代码。它正在通过webservice访问 – 2012-03-26 15:29:54