I have an action filter that is responsible for placing some common information into the ViewBag for use by all views in the shared _Layout.cshtml file.
public class ProductInfoFilterAttribute : ActionFilterAttribute
{
public override void
OnActionExecuting(ActionExecutingContext filterContext)
{
// build product info
// ... (code omitted)
dynamic viewBag = filterContext.Controller.ViewBag;
viewBag.ProductInfo = info;
}
}
In the shared _Layout.cshtml file, I use the information that has been put into the ViewBag.
...
@ViewBag.ProductInfo.Name
...
If an exception occurs while processing a controller action, the standard HandleErrorAttribute should display my shared Error.cshtml view, and this worked before I introduced the action filter above and started using the new values from ViewBag in _Layout.cshtml. Now what I get is the standard ASP.Net runtime error page instead of my custom Error.cshtml view.
I have tracked this down to the fact that while rendering the error view, a RuntimeBinderException ("Cannot perform runtime binding on a null reference") is thrown on the use of ViewBag.ProductInfo.Name in _Layout.cshtml.
It appears that even though my action filter has successfully set the value in the ViewBag before the original exception was thrown, a new context with an empty ViewBag is used when rendering my Error.cshtml view.
Is there any way to get data created by an action filter to be available to a custom error view?