Last post Mar 19, 2015 10:07 AM by CsharpAsp.net
Mar 17, 2015 04:34 AM|CsharpAsp.net|LINK
I have created custom attribute as:
[System.AttributeUsage(System.AttributeTargets.All, AllowMultiple = true)]
public class CustomPermission : Attribute
public CustomPermission (string perName)
protected String _name;
public String Name
I have this attribute on my method as:
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?
Mar 18, 2015 01:46 AM|CsharpAsp.net|LINK
Mar 18, 2015 06:33 PM|Paul Linton|LINK
You could have the called method check that the requirements of its own attribute are satisfied. This could be done with a preprocessing step that runs prior to compilation that transforms the source to inject the required checking code. Or you could add
a call to the checking routine as the first line of your called method (in which case you might as well delete the attribute)
Alternatively, you need to put a wrapper around all methods which may be called that have your attribute on them. The wrapper then checks that the Attribute's requirements are met. This is the approach that is normally taken. The various security attributes
in MVC work this way, for example. Before the framework calls Controller methods it checks that the various attributes attached to the method and/or class are satisfied.
I am not 100% sure what you mean by 'automatically check' but there is no switch for the compiler which means 'there could be attributes on some methods could you call a custom method if you find them"
Mar 18, 2015 11:22 PM|CsharpAsp.net|LINK
Thanks for the reply Paul.
I am not sure about the pre processing step as you mentioned.
This is not a MVC app I have.
By automatically I meant was instead having to manually check for the permission in each method.
ie instead of having a call in every method something like this CheckPermission("username")
What I want is whenever a call to my method is made, it checks for the permission attribute and accordingly moves forward.
Mar 18, 2015 11:38 PM|Paul Linton|LINK
Basically - no you can't. There is no such built-in mechanism (that I am aware of).
I was referring to MVC as an example of an environment where people might 'think' that what you want is happening. But if you don't know MVC then there is no point to the analogy
The pre-processing solution would be tricky, I don't recommend it unless you are already familiar with how to do this.
Mar 19, 2015 10:07 AM|CsharpAsp.net|LINK
I ill look into other options