Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ViewBag inside of Filters of ASP.NET Core

Based upon this post Make a Global ViewBag, I'm trying to implement the following in ASP.NET Core 2.2. I realize the original post was for MVC 3.

public class CompanyFilter : ActionFilterAttribute
{
    public override void OnActionExecuting(ActionExecutingContext filterContext)
    {
        filterContext.Controller.ViewBag.Company = "MyCompany";
    }
}

I'm unable to find in what namespace filterContext.Controller.ViewBag would be defined. Is this still available in ASP.NET Core?

like image 707
ffejrekaburb Avatar asked Dec 20 '18 22:12

ffejrekaburb


1 Answers

In ASP.NET Core, it's possible to define a controller class that does not inherit from either Controller or ControllerBase. Because of this, filterContext.Controller in your example is of type object instead of Controller. However, if the controller is actually an instance of Controller, you can just cast the Controller property and then use ViewBag accordingly. Here's an example:

if (filterContext.Controller is Controller controller)
    controller.ViewBag.Company = "MyCompany";

The use of is here is an example of pattern matching that was introduced in C# 7.

like image 134
Kirk Larkin Avatar answered Sep 24 '22 21:09

Kirk Larkin