【发布时间】:2010-12-02 04:50:53
【问题描述】:
我编写了一个动作过滤器,它检测新会话并尝试将用户重定向到一个页面,通知他们这已经发生。唯一的问题是我无法弄清楚如何让它重定向到动作过滤器中的控制器/动作组合。相反,我只能弄清楚如何重定向到指定的 url。有没有直接的方法来重定向到 mvc2 中动作过滤器中的控制器/动作组合?
【问题讨论】:
标签: asp.net-mvc redirect action-filter
我编写了一个动作过滤器,它检测新会话并尝试将用户重定向到一个页面,通知他们这已经发生。唯一的问题是我无法弄清楚如何让它重定向到动作过滤器中的控制器/动作组合。相反,我只能弄清楚如何重定向到指定的 url。有没有直接的方法来重定向到 mvc2 中动作过滤器中的控制器/动作组合?
【问题讨论】:
标签: asp.net-mvc redirect action-filter
您可以将过滤器上下文的 Result 设置为 RedirectToRouteResult,而不是直接在 ActionFilter 中获取对 HttpContent 的引用和重定向。它更干净,更适合测试。
像这样:
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
if(something)
{
filterContext.Result = new RedirectToRouteResult(
new RouteValueDictionary {{ "Controller", "YourController" },
{ "Action", "YourAction" } });
}
base.OnActionExecuting(filterContext);
}
【讨论】:
编辑:最初的问题是关于如何检测会话注销,然后自动重定向到指定的控制器和操作。然而,事实证明这个问题更有用,因为它是当前形式。
我最终使用了多个项目的组合来实现这个目标。
首先是找到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);
}
}
【讨论】:
使用this overload调用RedirectToAction:
protected internal RedirectToRouteResult RedirectToAction(
string actionName,
RouteValueDictionary routeValues
)
在动作过滤器中,故事有点不同。一个很好的例子,看这里:
http://www.dotnetspider.com/resources/29440-ASP-NET-MVC-Action-filters.aspx
【讨论】: