我在应用程序中使用过Asp.Net Identity框架,有必要在会话过期时给出提示信息,然后跳转到登录页面而不是直接跳转到登录页面。使用自定义样式提示信息。
因为我的应用程序的左侧菜单使用ajax加载视图,所以我重写了AuthorizeAttribute.HandleUnauthorizedRequest方法以返回json。现在,当用户单击左侧菜单时,它可以正常工作。但是,如果用户通过单击F5刷新页面,则该页面仍会直接跳转到登录页面。

我已经覆盖了AuthorizeAttribute.HandleUnauthorizedRequest

    protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext)
    {
        var httpContext = filterContext.HttpContext;
        string sintab = httpContext.Request["inTab"];

        if (!string.IsNullOrEmpty(sintab) && bool.Parse(sintab))
        {
            var result = new JsonResult();
            result.Data = new
            {
                Authorize = false,
                Url = LOGIN_URL
            };
            result.JsonRequestBehavior = JsonRequestBehavior.AllowGet;

            filterContext.Result =result;
            return;
        }
        if (filterContext.Controller.GetType() != typeof(Controllers.HomeController) &&
            !filterContext.ActionDescriptor.ActionName.Equals("Index", StringComparison.OrdinalIgnoreCase))
        {
            string returnUrl = "/" + filterContext.Controller.GetType().Name.Replace("Controller","") + "/Index" ;
            returnUrl = httpContext.Server.UrlEncode(returnUrl);
            httpContext.Response.Redirect("~/Account/Login?ReturnUrl="+returnUrl);
            return;
        }

        base.HandleUnauthorizedRequest(filterContext);
    }


左侧菜单的loadView js代码

        $.get(url, null, function (html) {
        html = html.replace(/#%/g, "\"").replace(/%#/g, "\"");
        var json;
        try {
            json = eval("(" + html + ")");
        } catch (e) {

        }
        if (json && !json.Authorize) {
            // give an message
            layer.alert("Session timeout, please re login.", function (index) {
                window.location.href = json.Url + "?returnurl=" + encodeURI(hash);
            });
        }
        else {
            $("#content").empty().html(html);
            _initModalButton();
            $("#content").show();
        }

    }, 'html');


该页面看起来像这张图片
javascript - 使用Asp.Net Identity时如何在重定向到登录 View 之前发出通知消息?-LMLPHP

我想知道是否有更好的方法来执行此操作,因为还有很多其他按钮需要检查授权状态并在跳转到登录页面之前显示消息,以及在用户刷新页面时如何显示消息?

非常感谢!

最佳答案

我认为您正在寻找的是Global Ajax活动。
请检查this,我认为这使您的工作更加轻松。

10-04 15:34