views:

22

answers:

1

Hi,

Is there a way of getting the Action, and reading any attributes, during the model binding phase?

The scenario is this:

I've got a default model binder set-up for a certain data-type, but depending on how it's being used (which is controlled via an attribute on the action) I need to ignore a set of data.

I can use the RouteData on the controller context and see the action name, which I can use to go get the data, but wondered if that information is already available.

Additionally, if the action in question is an asynchronous one, they'd be more processing involved in looking it up...

A: 

You could walk the stack trace and find the first method that returns an ActionResult and pull the attributes:

    StackTrace st = new StackTrace();
    for (int i = 0; i < st.FrameCount; i++)
    {
        StackFrame frame = st.GetFrame(i);
        MethodBase mb = frame.GetMethod();
        if (mb is MethodInfo)
        {
            MethodInfo mi = (MethodInfo)mb;
            if (typeof(ActionResult).IsAssignableFrom(mi.ReturnType))
            {
                object[] methodAttributes = mb.GetCustomAttributes(true);
                object[] objectAttributes = mb.DeclaringType.GetCustomAttributes(true);
            }
        }
    }

This would only work if you call UpdateModel after the action has been called not when the model is bound before reaching the action method.

jwsample
Unfortunately, it would need to work when the modelbinder gets called as part of constructing the parameters to an action.
Kieron