2012-07-19 40 views
0

我有一個MVC應用程序,它使用$ .ajax從控制器獲取數據。JQuery和MVC會話超時不重定向

不幸的是,當會話超時發生頁面不會重定向到登錄頁面。有人可以幫助解決這個問題嗎?

謝謝。

+0

你能向我們提供您獲得當會話超時AJAX應對? – 2012-07-19 05:45:34

回答

2

你可以寫一個自定義的[授權]屬性,該屬性將返回,而不是在未經授權的訪問情況下,這將允許客戶端腳本來處理拋出401異常JSON場景優雅:

AttributeUsage(AttributeTargets.Class | AttributeTargets.Method)] 
public class MyAuthorizeAttribute : AuthorizeAttribute 
{ 
    protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext) 
    { 
     if (filterContext.HttpContext.Request.IsAjaxRequest()) 
     { 
      filterContext.Result = new JsonResult 
      { 
       Data = new 
       { 
        // put whatever data you want which will be sent 
        // to the client 
        message = "sorry, but you were logged out" 

       }, 
       JsonRequestBehavior = JsonRequestBehavior.AllowGet 
      }; 
     } 
     else 
     { 
      base.HandleUnauthorizedRequest(filterContext); 
     } 
    } 
} 

在阿賈克斯你可以這樣做:

$.get('@Url.Action("SomeAction")', function (result) { 
    if (result.message) { 
     alert(result.message); 
     window.location.reload(); 
    } else { 
     // do whatever you were doing before with the results 
    } 
}); 
+0

代碼示例中的第一行缺少左方括號,應該是: [AttributeUsage(AttributeTargets.Class | AttributeTargets.Method)] – ChrisP 2013-06-06 16:20:47