保护ASP.NET MVC中的控制器操作

时间:2010-02-02 11:11:22

标签: c# asp.net asp.net-mvc-2

在ASP.NET MVC 2中,为了保护控制器操作,我创建了一个继承自RequirePermission类的类ActionFilterAttribute。控制器操作看起来像

[RequirePermission(permissions="CanView")]

    public ActionResult List()
    {
       ...
    }

我有一个名为Permissions

的枚举
public enum Permissions { CanDoEdit, CanView, CanInsert }

RequirePermission类看起来像

public class RequirePermission : ActionFilterAttribute
    {
        public string permissions;
        string[] param = { "," };
        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {

            string[] requirePermissions = permissions.Split(param, StringSplitOptions.RemoveEmptyEntries);


           if (requirePermissions.Contains(Permissions.CanDoEdit.ToString()))
           {
                     //Check permission 
           }
           if (requirePermissions.Contains(Permissions.CanView.ToString()))
           {
                     //Check permission 
           }
           if (requirePermissions.Contains(Permissions.CanInsert.ToString()))
           {
                    //Check permission 
           }
        }
    } 

现在我想使用RequirePermission属性,而不是制作不同的属性 [RequirePermission(permissions=Permissions.CanView+","+Permissions.CanEdit)]以便我可以将它用于不同的场景。但编译器会抛出以下错误。

属性参数必须是属性参数类型的常量表达式,typeof表达式或数组创建表达式

1 个答案:

答案 0 :(得分:4)

怎么样:

[Flags]
public enum Permissions 
{ 
    CanDoEdit = 1 << 0, 
    CanView = 1 << 1,
    CanInsert = 1 << 2
}

然后:

[RequirePermission(permissions = Permissions.CanView & Permissions.CanEdit)]

最后验证CanView是否已设置:

if ((requirePermissions & Permissions.CanView) == Permissions.CanView)
{
    // The user has CanView permission
}