当ajax请求返回FormsAuthentication.RedirectToLoginPage时,如何重新加载页面? [英] How to reload page when an ajax request returns FormsAuthentication.RedirectToLoginPage?

查看:232
本文介绍了当ajax请求返回FormsAuthentication.RedirectToLoginPage时,如何重新加载页面?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在asp.net mvc中使用表单身份验证时,我很难找出如何将ajax请求重定向到登录页面.

I am a little in a trouble to find out how to redirect an ajax request to the login page when using forms authentication in asp.net mvc.

在OnAuthorize方法中,我知道请求需要授权.如果由于超时等原因删除了cookie,我想将用户重定向到登录页面.但是一般来说,请求是通过ajax请求由jquery触发的.因此,请求将返回登录页面的html.

In OnAuthorize method I know that the request needs authorization. And if the cookie was deleted because of timeout etc., I want to redirect the user to the login page. But generally the requests are triggered by jquery via ajax request. So the requests are returning the html of the login page.

那么我如何将用户重定向到ajax请求的登录页面?有什么想法吗?

So how can I redirect the user to login page for an ajax request? Any ideas?

推荐答案

您可以编写一个自定义的authorize属性,该属性将测试请求是否为AJAX请求,如果是,则返回一个包含URL的JSON以重定向到:

You could write a custom authorize attribute which would test if the request was an AJAX request and if yes return a JSON containing the url to redirect to:

public class MyAuthorizeAttribute : AuthorizeAttribute
{
    protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext)
    {
        if (filterContext.HttpContext.Request.IsAjaxRequest())
        {
            // It was an AJAX request => no need to redirect
            // to the login url, just return a JSON object
            // pointing to this url so that the redirect is done 
            // on the client
            filterContext.Result = new JsonResult
            {
                JsonRequestBehavior = JsonRequestBehavior.AllowGet,
                Data = new { redirectTo = FormsAuthentication.LoginUrl }
            };
        }
        else
        {
            // standard request => redirect
            base.HandleUnauthorizedRequest(filterContext);
        }
    }
}

,然后在发出AJAX请求时:

and then when you make an AJAX request:

$.get('/foo', function(result) {
    if (result.redirectTo) {
        window.location.href = result.redirectTo;
    } else {
        // standard stuff
    }
});

并且当然要避免在每个AJAX调用中重复此操作,您可以使用 .ajaxComplete() 处理程序

and of course to avoid repeating this in every AJAX call you could use the .ajaxComplete() handler.

这篇关于当ajax请求返回FormsAuthentication.RedirectToLoginPage时,如何重新加载页面?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆