1

我希望改进我在 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 中,只需重新加载整个页面?”

谢谢。

4

1 回答 1

1

从 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()" 
     })
于 2012-05-18T21:13:51.543 回答