Creating custom Annotations in ASP.NET

Asked

Viewed 650 times

3

I own a Controller in my project (Web Service) I need to do a token check for each method request. One solution I found is to create a static method and place a call at each start of each method. I could put only once in the builder of mine Controller but here’s the problem: not all methods need this verification.

Then I would like to know how to implement an Annotations with my verification implementation 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
}

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 the action/controller

    [AuthorizeByMe]
    public ActionResult Skol()
    {
        //...
        return View();
    }
  • I think what he wants is not really an authentication. It’s kind of a custom token validation. Derive the [Authorize] would work well if his project wasn’t a Web Service.

  • I’m not sure about the type of project, because the question mentions a redirect to a 404 page, which makes little sense to a web-service.

  • It would only be valid if on the return of the web-service it was a call to a page, and on the return when invalid came the request to the 404

  • Michelangelo I mentioned a 404 return but not necessarily 404, it may be a custom json return informing the client that authentication via token failed.

3

In , we call "Annotations" of Attributes. Just as the Annotations of , Attributes are used to decorate classes, methods, properties, etc.

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

I intend to put a more complete solution soon. I am even preferring the question to return to it later. In any case, you can use the @tchicotti solution and derive the [Authorize].

Browser other questions tagged

You are not signed in. Login or sign up in order to post.