Get the name of the api method called from the authorization attribute

In my authorization attribute code, I would like to determine which WebAPI method was called.

I appreciate that I can do this by passing the name to (see example 2), but I would prefer not to.

// 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 any way that I can somehow raise it?

+4
source share
1 answer

If obtained from AuthorizeAttributeyou can access ActionDescriptorusingHttpActionContext

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);
    }
}
+4
source

Source: https://habr.com/ru/post/1689693/


All Articles