Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get an Asp.net Web API controller context or action context in an HttpModule

I have an HttpModule that is doing some processing on a request before the web api controller's action is executed. I'd like to be able to identify what controller/action will be executed by the request so I can examine some attributes that may be set on the controller/action ahead-of-time. How do I discover the controller/action that a particular requst URI will invoke?

In the HttpModule, obviously I can get the RouteData from the RouteTable -- how do I use this to find out the type (or preferably methodinfo, or at least method name) of the controller & action that will be invoked?

like image 824
Jordan0Day Avatar asked Nov 19 '25 18:11

Jordan0Day


2 Answers

An HttpModule is not a place where you should do such stuff. An HttpModule will be executed for every request regardless whether the request will go into the ASP.NET Web API pipeline or not.

What you need here is a Message Handler which will serve as smilar as an HttpModule for ASP.NET Web API requests.

like image 51
tugberk Avatar answered Nov 21 '25 08:11

tugberk


Here is a sample illustrating how to get an ActionDescriptor and ControllerDescriptor from RouteData:

    var routeData = RouteTable.Routes.GetRouteData(requestContext.HttpContext); 
    if (routeData == null) 
        return false; 
    var controllerName = (string)routeData.Values["controller"]; 
    var actionName = (string) routeData.Values["action"]; 
    var controller = ControllerBuilder.Current.GetControllerFactory().CreateController(requestContext, controllerName); 
    if (controller == null) 
        return false; 
    var controllerType = controller.GetType(); 
    var controllerDescriptor = new ReflectedControllerDescriptor(controllerType); 
    var actionDescriptors = controllerDescriptor.GetCanonicalActions(); 
like image 25
Kirill Bestemyanov Avatar answered Nov 21 '25 10:11

Kirill Bestemyanov



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!