简体   繁体   中英

Custom attribute and execute method

I have created custom attribute as:

[System.AttributeUsage(System.AttributeTargets.All, AllowMultiple = true)]
public class CustomPermission : Attribute
{
    public CustomPermission (string perName)
    {
        this._name= perName;
    }
    protected String _name;
    public String Name
    {
        get
        {
            return this._name;
        }
    }       
}

I have this attribute on my method as:

[CustomPermission("Allowed")]
public void GetData()
{
   //only comes here if permisson is allowed
   //logic for db 
}

I want whenever a call is made to GetData it automatically checks for the CustomPermission attribute over the method and accordingly grants/deny access.

How can I do that?

Thanks

To my understanding, what you would like to achieve is impossible to do with attributes. The best security that is possible with your approach would be to use reflection to look for the attribute before a client calls the method; however, this way the client decides whether it actually respects the restricted access rights or not, which is not access control.

You are probably going about this the wrong way altogether, but to access the metadata in your method, you'd have to do something like this:

[CustomPermission("Allowed")]
public void GetData()
{
   var mi = MethodInfo.GetCurrentMethod();
   var attr = mi.GetCustomAttribute<CustomPermission>();
   // now attr contains your CustomPermission
   if (attr.Name == "Allowed") 
   {
       //only comes here if permisson is allowed
       //logic for db 
   }
}

This is obviously a bit ugly and can be optimized some by storing the attribute somewhere so you don't have to find it every time. But either way, as others have commented, I don't think this is going to ultimately achieve what you want to do.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM