Saturday, 31 August 2013

Custom Attribute doesn't work in C#?

Custom Attribute doesn't work in C#?

I want to create an Attribute which will indicate who has the sufficient
permission to use the class .
So I created this :
[AttributeUsage(AttributeTargets.Class, AllowMultiple = false)]
public class AllowAttribute : Attribute
{
public AllowAttribute(params string[] allowedRoles)
{
IPrincipal user = Thread.CurrentPrincipal;
if (!allowedRoles.Any(user.IsInRole)) throw new Exception();
//here is the checking
}
}
And my testing class is :
[Allow(Roles.Administrator, Roles.OtherSampleRole)]
public class SamplePage
{
public void MyMethod()
{
Console.WriteLine("a");
}
}
(Roles.Administrator and Roles.OtherSampleRole are from here : )
public class Roles
{
public const string Administrator = "Administrator";
public const string OtherSampleRole = "OtherSampleRole";
}
Testing code ( which should fail) :
static void Main(string[] args)
{
Thread.CurrentPrincipal = new GenericPrincipal(new
GenericIdentity("Bob", "Passport"),
new[]
{
"lalala" // this value is invalid and should
fail at the attribute ctor
});
SamplePage sample = new SamplePage();
sample.MyMethod();
Console.ReadLine();
}
Question :
This is not working and I still see the output from the MyMethod method.
And I also can't get into (when debug mode) the ctor of the attribute.
What am I doing wrong ?

No comments:

Post a Comment