开发者

Attribute on method doesn't work

I have a method with an attribute (in c# library). The problem is that attribute is not call when I call my method. I don't understand why !

My code:

[AttributeUsage(System.AttributeTargets.Method)]
public class RequireAuthorization : System.Attribute
{
    private bool _protected = true;

    public RequireAuthorization(bool protect)
    {
        _pr开发者_运维技巧otected = protect;
    }
}

public class MyClass(){

    [RequireAuthorization(true)]
    public bool method1(){
       // some actions
    }
}

Some idea please?


Attributes are just metadata, they are jitted and part of your codebase, but they don't need to run.

To enforce running your custom Attribute you could use reflection, the following would cause the constructor of your RequireAuthorization class to be executed:

MemberInfo memberInfo = typeof(MyClass).GetMethod("method1");
var attributes = memberInfo.GetCustomAttributes(false);


Attributes are simply metadata and does not perform any sort of pre/post interception of method invocations.

For this to work, you need some interception mechanism, e.g. Post# or dynamic proxies etc.

See http://www.sharpcrafters.com/solutions/security

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜