Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can i get the MethodInfo of the controller action that will get called given a request?

I have a controller and action that's responsible for handling 403s due to the users not being in the correct roles. It has access to the original RequestContext that caused the exception.

What I would like to be able to do is decorate my actions with a description of what they do, then allow the user to notify their manager, requesting access including the description in an email.

So, how can I work out what action would be called given a RequestContext?

Obviously this is more complicated that getting controller and action names out of the RouteData since there are often overloads of an action method etc.

Once I have the MethodInfo then it's easy to get attributes etc.

like image 664
George Duckett Avatar asked May 30 '12 10:05

George Duckett


1 Answers

Here's an extension method for you. If you're doing dependency injection on your controllers (non-parameterless constructor), you'll need to enumerate the controller constructors with reflection, or use your IOC container to instantiate your controller, rather than using Activator.CreateInstance. Also, this can be modified to work with similar context's like ExceptionContext or HttpContext pretty easily.

public static class RequestContextExtensions
{
    public static MethodInfo GetActionMethod(this RequestContext requestContext)
    {
        Type controllerType = Assembly.GetExecutingAssembly().GetTypes().FirstOrDefault(x => x.Name == requestContext.RouteData.Values["controller"].ToString());
        ControllerContext controllerContext = new ControllerContext(requestContext, Activator.CreateInstance(controllerType) as ControllerBase);
        ControllerDescriptor controllerDescriptor = new ReflectedControllerDescriptor(controllerType);
        ActionDescriptor actionDescriptor = controllerDescriptor.FindAction(controllerContext, controllerContext.RouteData.Values["action"].ToString());
        return (actionDescriptor as ReflectedActionDescriptor).MethodInfo;
    }
}
like image 83
Devin Garner Avatar answered Sep 23 '22 14:09

Devin Garner