Mg.
Mg.

Reputation: 1467

How to know which controller method will be called from Web API Authorization filter

I have a custom AuthorizationFilter class to handle authorization to my API. Now, I need to enhance it by adding some attributes to methods which will be read only in some situations.

I can get the controller from actionContext.ControllerContext but:

How can I know which Controller method will be called from the IsAuthorized method of my custom AuthorizeAttribute class? So I can get it's attributes with reflection.

Edit: Adding more info-

If I get a call like localhost/api/myapi/?id=4 I want to get the real name of the method that will be executed in the controller like GetById(int id).

That way I could check if the method has any custom attributes I need added to it.

Upvotes: 10

Views: 9693

Answers (4)

Toby Simmerling
Toby Simmerling

Reputation: 2244

I used these to get all the descriptors and arguments within an ActionFilterAttribute

actionContext.ActionArguments["selectorString"] actionContext.ActionDescriptor.ControllerDescriptor.ControllerName actionContext.ActionDescriptor.ActionName

Upvotes: 1

Ananda Sudarshan
Ananda Sudarshan

Reputation: 485

Well you can try this from route Data

// Gets controller name    
var controller = routeData.GetRequiredString("controller");

// Gets action name
var action = routeData.GetRequiredString("action");

Upvotes: 0

Henrik Cooke
Henrik Cooke

Reputation: 775

In web api 2 you can access the action name with:

actionContext.ActionDescriptor.ActionName

Upvotes: 29

Joe
Joe

Reputation: 5487

You didn't post any code, but can't you look at the RouteData in the HttpActionContext?

 public class MyAuthAttribute : AuthorizeAttribute
 {
    protected override bool IsAuthorized(HttpActionContext actionContext)
    {
        var routeData = actionContext.ControllerContext.RouteData;

        //If you don't have an action name, I've assumed "index" is the default.
        var actionName = routeData.Values.ContainsKey("id") ? routeData.Values["id"].ToString() : "Index";

        //you can then get the method via reflection...
        var attribs = actionContext.ControllerContext.Controller.GetType()
                    .GetMethod(actionName, BindingFlags.Public | BindingFlags.Instance)
                    .GetCustomAttributes();

        //Do something...

        return base.IsAuthorized(actionContext);
    }
}

Upvotes: 1

Related Questions