How can I get the MethodInfo of the controller action that will be called upon request?

I have a controller and actions that are responsible for handling 403s due to the fact that users are not in the right roles. It has access to the original RequestContext that caused the exception.

What I would like to do is to decorate my actions with a description of what they are doing, and then let the user notify their manager by requesting access, including a description in the email.

So, how can I determine which action will be called using RequestContext ?

Obviously, this is more complicated, because getting the controller names and actions from RouteData , as often overloads of the action method, etc.

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

+4
source share
3 answers

Trying to work with it retrospectively is a bit of a worm’s ability, since you will probably need to use reflection to find the right method. It would probably be easier to insert the necessary data into the HttpContext.Items as part of the code in which the authorization fails? It will then be accessible from your processing method using RequestContext.HttpContext.Items .

+2
source

Here is the extension method. If you inject dependencies on your controllers (parameterless constructor), you will need to list the controller constructors with reflection or use your IOC container to instantiate your controller, instead of using Activator.CreateInstance. In addition, this can be changed to work with a similar context, such as ExceptionContext or HttpContext, quite 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; } } 
+7
source

I answered my question, it is very similar to this.

If this still interests you, perhaps I can penetrate deeper into it.

My question did not start with a URL like yours, but from the names of the controllers and actions, as well as the http method (GET, POST ...).

0
source

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


All Articles