Question

In ASP.NET Core (RC1) I am setting a ViewBag value in the OnActionExecuting method in a custom ActionFilter. This is the code:

public override void OnActionExecuting(ActionExecutingContext filterContext)
{
    filterContext.Controller.ViewBag.SomeValue = somevalue;
    base.OnActionExecuting(filterContext);
}

I am porting the code over from MVC 5 where is worked fine. In .NET Core RC1 the editor and compiler don't recognize the ViewBag property on the Controller. So, the code does not even compile.

Interestingly, when debugging (without the ViewBag assignment) the ViewBag property is visible on the Controller! What gives? How come the compiler and the run-time are different?

1 Answers

I ran into the same issue. Here is what is going on.

Look at the definition of the ActionExecutingContext:

public class ActionExecutingContext : FilterContext
{
    public ActionExecutingContext(ActionContext actionContext, IList<IFilterMetadata>
           filters, IDictionary<string, object> actionArguments, object controller);

    public virtual IDictionary<string, object> ActionArguments { get; }
    public virtual object Controller { get; }
    public virtual IActionResult Result { get; set; }
}

Notice that Controller is typed as an object, rather than a Controller class. I am not sure why this is different from the original ASP.NET MVC, but it explains the discrepancy between compile time and runtime.

The solution is to cast the Controller property to a Controller class.

Hope this helps.