2009-09-29 93 views
39

我已经写了一个动作过滤器,它检测到一个新的会话,并尝试将用户重定向到一个页面,通知他们已经发生了。唯一的问题是我无法弄清楚如何将它重定向到动作过滤器中的控制器/动作组合。我只能找出如何重定向到指定的网址。有没有一种直接的方式来重定向到mvc2中的动作过滤器中的控制器/动作组合?重定向到指定的控制器和动作在asp.net mvc动作过滤器

回答

87

而不是前往HttpContent参考,并直接在ActionFilter重定向您可以设置过滤背景的结果是一个RedirectToRouteResult。这对测试来说更清洁一点。

像这样:

public override void OnActionExecuting(ActionExecutingContext filterContext) 
{ 
    if(something) 
    { 
     filterContext.Result = new RedirectToRouteResult(
      new RouteValueDictionary {{ "Controller", "YourController" }, 
             { "Action", "YourAction" } }); 
    } 

    base.OnActionExecuting(filterContext); 
} 
+1

我的头受伤了,现在不是。谢谢 – jolySoft 2011-11-16 11:44:18

+3

这比我的答案更合适。这是我第一个关于MVC的问题,今天我会这样回答。 – 2012-01-10 12:56:10

4

呼叫RedirectToAction使用this overload

protected internal RedirectToRouteResult RedirectToAction(
    string actionName, 
    RouteValueDictionary routeValues 
) 

在操作过滤器,这个故事是有点不同。对于一个很好的例子,在这里看到:

http://www.dotnetspider.com/resources/29440-ASP-NET-MVC-Action-filters.aspx

+0

这是一个很好的地方去寻找一个动作过滤器(+1)重定向,但我真的想指定控制器/动作组合到我的过滤器。我也不想在自定义路由的情况下串接字符串,但我最终发现了一些可以提供帮助的东西。看到我的答案。 – 2009-10-01 13:18:03

17

编辑:原来的问题是关于如何检测会话注销,然后自动重定向到指定的控制器和动作。这个问题证明更有用,因为它是目前的形式。


我最终使用项目组合来实现此目标。

首先是会话过期发现过滤器here。然后,我想要指定控制器/操作组合来获取重定向URL,我发现了很多here的示例。最后我想出了这一点:

public class SessionExpireFilterAttribute : ActionFilterAttribute 
{ 
    public String RedirectController { get; set; } 
    public String RedirectAction { get; set; } 

    public override void OnActionExecuting(ActionExecutingContext filterContext) 
    { 
     HttpContext ctx = HttpContext.Current; 

     if (ctx.Session != null) 
     { 
      if (ctx.Session.IsNewSession) 
      { 
       string sessionCookie = ctx.Request.Headers["Cookie"]; 
       if ((null != sessionCookie) && (sessionCookie.IndexOf("ASP.NET_SessionId") >= 0)) 
       { 
        UrlHelper helper = new UrlHelper(filterContext.RequestContext); 
        String url = helper.Action(this.RedirectAction, this.RedirectController); 
        ctx.Response.Redirect(url); 
       } 
      } 
     } 

     base.OnActionExecuting(filterContext); 
    } 
} 
+7

如果你想使这更可测试,我相信你可以简单地设置filterContext.Result到一个RedirectResult,而不是明确的重定向。最终的结果是MVC仍然会执行重定向,但这样你可以编写单元测试,手动调用OnActionExecuting(),然后对filterContext.Result进行断言。 – 2010-01-05 19:38:44

相关问题