1

I have an ASP.NET MVC app that I am trying to migrate to MVC 6 (ASP.NET 5). With that in mind, I have some filters that were added using the process described in this SO post. However, with Global.asax being replaced with Startup.cs, I'm not sure where to add my global filters anymore.

In addition, in my filter I have:

public override void OnResultExecuting(ResultExecutingContext context)
{
  context.Controller.ViewBag.MyProperty = "[TESTING]";
}

When I run dnx . run now, I get an error that says:

MyFilter.cs(11,22): error CS1061: 'object' does not contain a definition for 'ViewBag' and no extension method 'ViewBag' accepting a first argument of type 'object' could be found (are you missing a using directive or an assembly reference?)

How do I add global filters in ASP.NET 5 (MVC 6)?

Community
  • 1
  • 1
Some User
  • 5,257
  • 13
  • 51
  • 93
  • I haven't used vNext yet, but it sounds like controllers can be POCO objects. I have no idea how `ViewBag` works in that design, but I suspect that's where your problem is actually occurring. If it can be a POCO object, `context.Controller` has to be an `object`, which can't be guaranteed by the compiler to have the property you've listed. I'd suggest looking into how to register `ViewBag` elements, and potentially just even write a class specifically for what you want to register and DI it into each controller. But again, I haven't used any of this, I just know what I heard from //build/. – Matthew Haugen May 16 '15 at 17:45

1 Answers1

4

To register global filter you can do following:

public void ConfigureServices(IServiceCollection services)
{
    services.AddMvc().Configure<MvcOptions>(options =>
    {
        options.Filters.Add(new YourCustomFilter());
    });
}

in your Startup.cs

Regarding error you're getting, context.Controller has object type and therefore ViewBag property can't be resolved. Cast it to Controller type first:

public override void OnResultExecuting(ResultExecutingContext context)
{
    var controller = (Controller) context.Controller;

    controller.ViewBag.MyProperty = "[TESTING]";
}
Andriy Horen
  • 2,861
  • 4
  • 18
  • 38