Creating Custom Annotations in ASP.NET

3

I have Controller in my project (Web Service) I need to do a token check to request each method. One solution I found is to create a static method and place a call at the beginning of each method. I could only put it once in the constructor of my Controller but that's the problem: not all methods need this verification.

So I would like to know how to implement an Annotations with the implementation of my verification and use Annotations to validate these requests. If the request is invalid, the request is sent to a 404 page.

I would like a horizon of how to do this, something like this pseudo-code below:

@VerificationToken
public List<Produto> getAllProducts(){
  // implementação
}
    
asked by anonymous 14.03.2014 / 13:45

2 answers

4

One solution to this would be to create your CustomAuthorizeAttribute inheriting from AuthorizeAttribute

Imagine for example something like AuthorizeByMe

would look like this:

  public class AuthorizeByMeAttribute : AuthorizeAttribute {

      protected override bool AuthorizeCore(HttpContextBase httpContext)
      {
          return true;           
      }
  }

and in action / controller

    [AuthorizeByMe]
    public ActionResult Skol()
    {
        //...
        return View();
    }
    
14.03.2014 / 13:54
3

At , we call "Annotations" of Attributes . Like , Attributes serve to decorate classes, methods, properties, etc.

But an Attribute is a special class that needs to be called by another to work. In your case, what you want is to call the method, but before that, a condition is tested before the method. This is done by implementing a Dynamic Proxy , making a override in the method Invoke of this Proxy class.

I want to put a more complete solution soon. I'm even favoring the point to get back to her later. In any case, you can use the @tchicotti solution and derive [Authorize] .

    
14.03.2014 / 16:31