开发者

Securing controller action in ASP.NET MVC

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.ToStri开发者_StackOverflowng()))
           {
                     //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


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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜