[英]ASP.NET 5 (vNext) - Using Filters
我有一个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
现在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)中添加全局过滤器?
要注册全局过滤器,您可以执行以下操作:
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc().Configure<MvcOptions>(options =>
{
options.Filters.Add(new YourCustomFilter());
});
}
在您的Startup.cs中
关于您遇到的错误, context.Controller
具有对象类型,因此无法解析ViewBag属性。 首先将其转换为控制器类型:
public override void OnResultExecuting(ResultExecutingContext context)
{
var controller = (Controller) context.Controller;
controller.ViewBag.MyProperty = "[TESTING]";
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.