【问题标题】:How to redirect an Ajax Method session on timeout如何在超时时重定向 Ajax 方法会话
【发布时间】:2012-10-31 15:55:38
【问题描述】:

所以我得到了一个返回 JSON 结果的 ajax 方法,但是该方法的一部分是检查会话是否有效。

所以如果用户刷新了一个页面,就会调用 ajax 方法,当会话过期时它会抛出一个异常,现在该方法想要返回 JSON 结果,但我想将它们重定向到登录页面.

我该怎么做?

public JsonResult GetClients()
{
var usertoken = new UserToken(this.User.Identity.Name);
if (usertoken.AccountId != null)
{
return new JsonResult() {Data = model, JsonRequestBehavior = JsonRequestBehavior.AllowGet};
}
else
{
 //Redirect Here
}

【问题讨论】:

标签: asp.net-mvc


【解决方案1】:

在控制器代码中,检查会话有效性。例如

        if (Session["UserName"] == null)
        {
            return Json(new
            {
                redirectUrl = ConfigurationManager.AppSettings["logOffUrl"].ToString(),
                isTimeout = true
            });
        }

在 .js 文件中检查如下

    success: function (data) {
        if (data != '' && typeof data != 'undefined') {
            if (data.isTimeout) {
                window.location.href = data.redirectUrl;
                return;
            }

【讨论】:

    【解决方案2】:

    AFAIK 您只能通过 JavaScript 执行此操作,因为您的调用使用 ajax,其他帖子的解决方案将不起作用,因为 ajax 请求不会尊重重定向标头。

    您可能希望在返回结果中添加 status 或 hasExpire 属性:

    [HttpPost]
    public ActionResult GetClients()
    {
    var usertoken = new UserToken(this.User.Identity.Name);
    if (usertoken.AccountId != null)
    {
    return Json(new { data = model, status = true });
    }
    else
    {
      return Json(new { data = null, status = false });
    }
    

    在您的 ajax 调用中:

    $.ajax('/controller/getclients', { }, function(data) {
      if(data.status == true) {
        // same as before you've got your model in data.data...
      } else {
        document.location.href = '/account/login';
      }
    });
    

    希望有所帮助。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-02-17
      • 1970-01-01
      • 2013-06-08
      • 2014-06-23
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多