ActionDescriptor from ControllerContext
Asked Answered
S

1

15

Given I have access only to ControllerContext and not Action____Contexts what is the optimal way to get the current executing ActionDescriptor?

So far the only method I've found is:

new ReflectedControllerDescriptor(context.Controller.GetType())
    .FindAction(context, context.RouteData.GetRequiredString("action"));

Is this the optimal method?

The fact that class is named ReflectedControllerDescriptor leads me to wonder if there is a heavy cost to this operation as it will be executed on every page request? Related to that is does this class internally cache or should I actually be caching ReflectedControllerDescriptors explicitly?

Strophic answered 30/5, 2012 at 20:12 Comment(5)
Doing some digging into the MVC source that's pretty much the most optimal way without copying all the methods required to do what you're already doing. However, I don't see why you couldn't cache found actions so that subsequent actions are more performant.Spanner
In addition the ReflectedControllerDescriptor does use reflection to get Actions since it not only looks at the methods but attributes attached to the methods as well. (the ReflectedControllerDescriptor also caches the results)Spanner
@BuildStarted so the the reflection usage inside of ReflectedControllerDescriptor is indeed cached, but arguably I could cache my calls to FindAction?Strophic
Yeah, you could. There is still some additional processing on attributes (even with cached actions) in the ReflectedControllerDescriptor but it doesn't appear to be anything process intensive.Spanner
This helped me get access to the ActionDescriptor from an IExceptionFilter, from which the ControllerContext is available, thanks.Sauerbraten
S
9

Doing some digging into the MVC source that's pretty much the most optimal way without copying all the methods required to do what you're already doing. However, I don't see why you couldn't cache found actions so that subsequent calls are more performant.

Internally ReflectedControllerDescriptor also caches the results though there seems to be a bit of overhead since it checks all attributes each time. It looks to be for stuff like HttpPostAttribute and what not.

My suggestion would be to stick with what you're using rather than cache it yourself. If, for some reason, the way the underlying method works changes you're up to date already and wont' have to worry about changing the way you store cached items.

Spanner answered 1/6, 2012 at 17:51 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.