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.
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;
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With