Get name of api method called from authorization attribute

Viewed 838

Within my custom authorization attribute code I would like to identify which WebAPI method has been called.

I appreciate that I could do this by passing the name in (see example 2) but I would rather not have to do this.

// Example1
[CustomAuthAttribute]
public MyResponse get(string param1, string param2)
{
    ...
}
// in the prev example I would like to be able to identify the
// method from within the CustomAuthAttribute code


// Example2
[CustomAuthAttribute(MethodName = "mycontroller/get")]
public MyResponse get(string param1, string param2)
{
    ...
}
// in this example I pass the controller/method names to the
// CustomAuthAttribute code

Is there a way I can somehow pick this up?

1 Answers

If derived from the AuthorizeAttribute you can access the ActionDescriptor via the HttpActionContext

public class CustomAuthAttribute : AuthorizeAttribute {    
    public override void OnAuthorization(HttpActionContext actionContext) {
        var actionDescriptor = actionContext.ActionDescriptor;
        var actionName = actionDescriptor.ActionName;
        var controllerName = actionDescriptor.ControllerDescriptor.ControllerName;
        //MethodName = "mycontroller/get"
        var methodName = string.Format("{0}/{1}", controllerName, actionName);
    }
}
Related