What is a django middleware equivalent in ASP MVC?

天大地大妈咪最大 提交于 2019-12-12 01:37:11

问题


Basically, I want to inject some data into ViewData/ViewBag for every single request.


回答1:


In ASP.NET MVC that would be an action filter. And if you want to do it globally you could register it as a global action filter. This way it will apply to all controller actions so that you don't need to decorate them individually.

So your filter could be defined like this:

public class GlobalViewBagInjectorActionFilter : ActionFilterAttribute
{
    public override void OnActionExecuted(ActionExecutedContext filterContext)
    {
        filterContext.Controller.ViewBag.Foo = "bar";
    }
}

and registered in the RegisterGlobalFilters method in your Global.asax:

public static void RegisterGlobalFilters(GlobalFilterCollection filters)
{
    filters.Add(new HandleErrorAttribute());
    filters.Add(new GlobalViewBagInjectorActionFilter());
}

Now inside all your views you can use the ViewBag.Foo property.

But in most situations Child Actions are a better alternative than ViewBag as they allow you to pass strongly typed view models instead of relying on this weakly typed ViewBag and some magic strings.



来源:https://stackoverflow.com/questions/11538753/what-is-a-django-middleware-equivalent-in-asp-mvc

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!