Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Checking custom attribute parameters at design/build time

I have a CustomAuthorize attribute that checks to see if a user has access to functionality (a user or role can be associated with items from a hierarchical set of functions).

For a given action method...

[CustomAuthorize("Security.Admin.ManageWidgets.Update")]

This works but I'm concerned that changes to the Security object could cause problems that won't be detected until run-time. I realize that I can write unit tests to mitigate this risk but I would like to know if it is possible to check the attribute parameter at compile time. I also like having Intellisense help me type this expression.

Ideally, I could pass a lambda expression.

[CustomAuthorize(i => i.Admin.ManageWidgets.Update)]

Unfortunately this is not currently possible (additional info from Microsoft).

I also tried encapsulating the expression hoping it would be evaluated and then passed to the attribute as a string, but this also failed to compile with the same error (Expression cannot contain anonymous methods or lambda expressions).

[CustomAuthorize(LambdaToString(i => i.Admin.ManageWidgets.Update))]

How can I add some design-time / build-time support for my custom attribute parameters?

like image 877
Mayo Avatar asked Jul 20 '11 15:07

Mayo


2 Answers

A Static class with constants.

public static class Rights
{
    public const string UpdateWidgets = "UpdateWidgets";
}

Also include unittests for the methods which are decorated with them and you'll be pretty good.

[CustomAuthorize(Rights.UpdateWidgets)]
like image 158
BennyM Avatar answered Sep 23 '22 21:09

BennyM


You can use T4 templates to create custom classes with string properties, ending up with code similar to BennyM's, but generated automatically.

like image 43
George Duckett Avatar answered Sep 22 '22 21:09

George Duckett