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?
You can use T4 templates to create custom classes with string properties, ending up with code similar to BennyM’s, but generated automatically.