title: How can I use data placed into a ViewBag by a filter in my Error.cshtml view?
body: <p>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.</p>
  
  <pre><code>public class ProductInfoFilterAttribute : ActionFilterAttribute
  {
      public override void
      OnActionExecuting(ActionExecutingContext filterContext)
      {
          //  build product info
          //  ... (code omitted)
  
          dynamic viewBag = filterContext.Controller.ViewBag;
          viewBag.ProductInfo = info;
      }
  }
  </code></pre>
  
  <p>In the shared _Layout.cshtml file, I use the information that has been put into the ViewBag.</p>
  
  <pre><code>...
  @ViewBag.ProductInfo.Name
  ...
  </code></pre>
  
  <p>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.</p>
  
  <p>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.</p>
  
  <p>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.</p>
  
  <p>Is there any way to get data created by an action filter to be available to a custom error view?</p>