2012-11-12 40 views
0

因此,我得到了一個返回JSON結果的ajax方法,但方法的一部分是檢查會話是否有效。如何在超時時重定向Ajax Method會話

所以如果用戶刷新一個頁面,那麼會調用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 
} 
+0

.js文件中查見這個問題:http://stackoverflow.com/questions/5102964/how-to-redirect-to-new-page -after-jQuery的Ajax的通話中MVC-如果會話超時 –

回答

1

據我所知,你只能夠因爲你的電話正在使用AJAX通過JavaScript要做到這一點,解決其他職位是行不通的,因爲重定向頭不會被兌現了一個Ajax請求。

您可能需要一個狀態或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'; 
    } 
}); 

希望可以幫助。

0

在控制器代碼中,檢查會話有效性。例如

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

在像下面

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