문제

I have an action filter which (among other things), adds stuff to the RouteData. The value, however, is not picked up by the parameter in my action method. Any ideas why?

Action Filter:

public class SomeFilter : FilterAttribute, IActionFilter
{
    public void OnActionExecuting(ActionExecutingContext filterContext)
    {
        var someData = new SomeClass();
        //do stuff
        filterContext.RouteData.Values["someData"] = someData;
     }
}

Action Method:

[SomeFilter]
public ViewResult SomeActionMethod(SomeClass someData)
{
  //someData is null here
}

Please note that the following line inside my action method does return something the data saved into it in action filter:

SomeClass isNotNull = RouteData.Values["someData"] as SomeClass;

Anyone knows why?

도움이 되었습니까?

해결책

The filter is attached to the action (method). Hence by the time the filter is run, the values for the parameters have already been chosen. Imagine the situation if what you asked worked:

[SomeFilter]
public ViewResult SomeActionMethod()
{
    // ....
}

public ViewResult SomeActionMethod(SomeClass someData)
{
    // .....
}

You reference http://mysite.com/mycontroller/SomeActionMethod with no query parameter. So then it should call the first action. But if your filter were to do what you wanted, after it ran, it should call the second action. But that one DOESN'T have the filter, so it should call the first. And round & round.

다른 팁

Here's an article that covers how to modify the Parameter values from an Action Filter:

http://haacked.com/archive/2010/02/21/manipulating-action-method-parameters.aspx/

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top