ffejrekaburb
ffejrekaburb

Reputation: 731

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?

Upvotes: 9

Views: 3146

Answers (1)

Kirk Larkin
Kirk Larkin

Reputation: 93063

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.

Upvotes: 9

Related Questions