我有一个ASP.NET MVC应用程序,我正在尝试迁移到MVC 6(ASP.NET 5)。考虑到这一点,我有一些使用此SO post中描述的过程添加的过滤器。但是,将Global.asax替换为Startup.cs,我不知道在哪里添加我的全局过滤器。
另外,在我的过滤器中我有:
public override void OnResultExecuting(ResultExecutingContext context)
{
context.Controller.ViewBag.MyProperty = "[TESTING]";
}
当我现在运行dnx . run
时,我收到一条错误消息:
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?)
如何在ASP.NET 5(MVC 6)中添加全局过滤器?
答案 0 :(得分:4)
要注册全局过滤器,您可以执行以下操作:
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc().Configure<MvcOptions>(options =>
{
options.Filters.Add(new YourCustomFilter());
});
}
关于您获得的错误,context.Controller
具有对象类型,因此无法解析ViewBag属性。首先将它转换为Controller类型:
public override void OnResultExecuting(ResultExecutingContext context)
{
var controller = (Controller) context.Controller;
controller.ViewBag.MyProperty = "[TESTING]";
}