0
基本上,我想为每个请求注入一些数据到ViewData/ViewBag中。什么是ASP MVC中的django中间件等效物?
基本上,我想为每个请求注入一些数据到ViewData/ViewBag中。什么是ASP MVC中的django中间件等效物?
在ASP.NET MVC中,这将是一个action filter。如果你想在全球范围内完成,你可以将其注册为global action filter。这样它将适用于所有控制器操作,因此您不需要单独装饰它们。
所以,你的过滤器,可以这样定义:
public class GlobalViewBagInjectorActionFilter : ActionFilterAttribute
{
public override void OnActionExecuted(ActionExecutedContext filterContext)
{
filterContext.Controller.ViewBag.Foo = "bar";
}
}
,并在RegisterGlobalFilters
方法在Global.asax
注册:
public static void RegisterGlobalFilters(GlobalFilterCollection filters)
{
filters.Add(new HandleErrorAttribute());
filters.Add(new GlobalViewBagInjectorActionFilter());
}
现在,所有的意见里面,你可以使用ViewBag.Foo
属性。
但是在大多数情况下,Child Actions是比ViewBag
更好的替代方案,因为它们允许您传递强类型的视图模型,而不是依赖于弱类型的ViewBag和一些魔法字符串。
我看过孩子的行为,但是让我失望的是,我仍然需要在路由中为它定义url。这对我没有意义。 – Kugel 2012-07-18 10:04:39