重定向从行为过滤器属性 [英] Redirect From Action Filter Attribute

查看:137
本文介绍了重定向从行为过滤器属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

什么是做在 ActionFilterAttribute 重定向的最佳途径。我有一个 ActionFilterAttribute 名为 IsAuthenticatedAttributeFilter 和检查会话变量的值。如果变量是假的,我希望应用程序重定向到登录页面。我想preFER使用路由名称 SystemLogin 然而,在这一点上的任何重定向的方法就可以了重定向。

What is the best way to do a redirect in an ActionFilterAttribute. I have an ActionFilterAttribute called IsAuthenticatedAttributeFilter and that checked the value of a session variable. If the variable is false, I want the application to redirect to the login page. I would prefer to redirect using the route name SystemLogin however any redirect method at this point would be fine.

推荐答案

设置filterContext.Result

随着路由名称:

filterContext.Result = new RedirectToRouteResult("SystemLogin", routeValues);

您也可以这样做:

filterContext.Result = new ViewResult
{
    ViewName = SharedViews.SessionLost,
    ViewData = filterContext.Controller.ViewData
};


如果你想使用RedirectToAction:


If you want to use RedirectToAction:

您可以使你的控制器(preferably其基础控制器),简单地调用来自System.Web.Mvc.Controller保护RedirectToAction在公共RedirectToAction方法。添加此方法允许公共调用的的从过滤器RedirectToAction。

You could make a public RedirectToAction method on your controller (preferably on its base controller) that simply calls the protected RedirectToAction from System.Web.Mvc.Controller. Adding this method allows for a public call to your RedirectToAction from the filter.

public new RedirectToRouteResult RedirectToAction(string action, string controller)
{
    return base.RedirectToAction(action, controller);
}

那么你的过滤器看起来是这样的:

Then your filter would look something like:

   public override void OnActionExecuting(ActionExecutingContext filterContext)
   {
       var controller = (SomeControllerBase) filterContext.Controller;
       filterContext.Result = controller.RedirectToAction("index", "home");
   }

这篇关于重定向从行为过滤器属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆