Note that there are some explanatory texts on larger screens.

plurals
  1. POc# execute code inside custom attribute
    text
    copied!<blockquote> <p><strong>Possible Duplicate:</strong><br> <a href="https://stackoverflow.com/questions/1164978/why-does-my-net-attribute-not-perform-an-action">Why does my .NET Attribute not perform an action?</a> </p> </blockquote> <p>Hi,</p> <p>This may soundlike a very dumb question and I don't know what is possible here as all the "custom attribute" tutorials on the net are pretty much the same and they don't address what I want to do. I've seen some code out there where code is written inside attribute classes, eg: <a href="http://www.singingeels.com/Articles/Logging_with_ASPNET_MVC_Action_Filters.aspx" rel="nofollow noreferrer">Logging with ASP.NET MVC Action Filters</a> and I am wondering how this code is ever executed.</p> <p>If I have for example the following code:</p> <pre><code>public class Test { [RestrictedAttribute("RegisteredMember")] public void DoSomething() { //this code can only be executed if the logged-in user //is a member of the RegisteredMember group } } </code></pre> <p>Then the custom Attribute RestrictedAttribute would be something like this:</p> <pre><code>[AttributeUsage(AttributeTargets.Method)] public class RestrictedAttribute : System.Attribute { /// &lt;summary&gt; /// Make this code restricted to users with a required role /// &lt;/summary&gt; /// &lt;param name="requiredRole"&gt;The role required to execute this method&lt;/param&gt; public RestrictedAttribute(string requiredRole) { //validate if member is in role, else throw exception throw new MemberNotInRoleException(requiredRole); } public new string ToString() { return "Access needs to be granted"; } } </code></pre> <p>Now the problem is that I can't get the MemberNotInRoleException to be thrown when I execute the Test.DoSomething() method.</p> <p>Perhaps I am just missing the entire concept of custom attributes, feel free to explain.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload