RedirectToRouteResult刷新页面而不是更新div

时间:2012-05-18 21:11:51

标签: asp.net-mvc

我希望改进我在asp.net MVC中的页面身份验证处理,所以我正在阅读本指南(http://markfreedman.com/index.php/2012/02/28/handling-session-and-authentication-timeouts-in-asp-net-mvc/)并尝试了他的例子:

[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, Inherited = true, AllowMultiple = true)]
public class SessionExpireFilterAttribute : ActionFilterAttribute
{
    public override void OnActionExecuting(ActionExecutingContext filterContext)
    {
        HttpContext ctx = HttpContext.Current;

        // If the browser session or authentication session has expired...
        if (ctx.Session["UserName"] == null || !filterContext.HttpContext.Request.IsAuthenticated)
        {
            if (filterContext.HttpContext.Request.IsAjaxRequest())
            {
                // For AJAX requests, we're overriding the returned JSON result with a simple string,
                // indicating to the calling JavaScript code that a redirect should be performed.
                filterContext.Result = new JsonResult { Data = "_Logon_" };
            }
            else
            {
                // For round-trip posts, we're forcing a redirect to Home/TimeoutRedirect/, which
                // simply displays a temporary 5 second notification that they have timed out, and
                // will, in turn, redirect to the logon page.
                filterContext.Result = new RedirectToRouteResult(
                    new RouteValueDictionary {
                        { "Controller", "Home" },
                        { "Action", "Index" }
                });
            }
        }

        base.OnActionExecuting(filterContext);
    }
}

但我注意到我的许多链接都是Ajax.ActionLinks,如下所示:

<ul>@Ajax.ActionLink("Employees", "Index", "Employee", new AjaxOptions { UpdateTargetId = "employee_detail" })</ul>

执行此操作时,登录视图在身份验证到期后正确返回,但在页面div中返回,而不是重新加载整个页面。是否可以在视图中设置?要说“如果我在div中,只需重新加载整个页面?”

感谢。

1 个答案:

答案 0 :(得分:1)

根据documentation of Ajax.ActionLink判断,如果返回非200状态代码,则会调用OnFailure。在您的属性中,请务必添加状态代码,类似于:

filterContext.Result = new JsonResult { Data = "_Logon_" };
filterContext.HttpContext.Response.StatusCode = (int)HttpStatusCode.Unauthorized;

一旦在那里,OnFailure脚本名称可以添加到你的ActionLink:

@Ajax.ActionLink("Employees", "Index", "Employee", 
    new AjaxOptions { 
      UpdateTargetId = "employee_detail", 
      OnFailure="myRedirectFunctionName()" 
     })