views:

273

answers:

1

In ASP.NET MVC 2, to secure controller action, i have created a class RequirePermission inherited from ActionFilterAttribute class. The controller action looks like

[RequirePermission(permissions="CanView")]

    public ActionResult List()
    {
       ...
    }

I have an enum with name Permissions

public enum Permissions { CanDoEdit, CanView, CanInsert }

The RequirePermission class looks like

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 
           }
        }
    } 

Now instead of making different attributes , I want to use RequirePermission attribute like [RequirePermission(permissions=Permissions.CanView+","+Permissions.CanEdit)] so that i can use it for different scenerious. but the compiler throw the following error.

An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type

+3  A: 

How about:

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

And then:

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

And finally to verify that CanView is set:

if ((requirePermissions & Permissions.CanView) == Permissions.CanView)
{
    // The user has CanView permission
}
Darin Dimitrov
Thank you very much.
Adeel
Darin Dimitrov
i think you are wrong. To set both permissions, use Permissions.CanView | Permissions.CanEdit. But to avoid overwriting the enum values, i have set the values in pover of 2.
Adeel