4

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?

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Yeah, the more I research this, the more it looks like this is the route I have to take, if I want to use any contextual information from the controller/action description. I was hoping to do as much as possible in the httpmodule level, to short-circuit any calls into the WebAPI-based stuff if they weren't needed (that is, is the caller wasn't authenticated).
1

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(); 

4 Comments

Does ControllerBuilder have an analog in Web API?
ApiController is Controller afaik.
Yes, I mean the "ControllerBuilder" type -- it seems to be in System.Web.Mvc, but I don't see anything like that in System.Web.Http.
this is completely wrong. ASP.NET Web API has nothing to do with ASP.NET MVC (in other words, System.Web.Mvc).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.