2011-11-29 91 views
5

我有一個Ajax.ActionLink,這會導致返回部分視圖。但是,如果我的FormsAuthentication過期並且用戶需要再次登錄,則整個登錄頁面將作爲部分視圖返回。當用戶需要重新登錄時,Ajax.ActionLink返回div內的登錄頁面

這會導致完整的登錄頁面出現在爲局部視圖預留的div中。所以它看起來像在頁面上的兩個網頁。

我在我的控制器和操作上使用[Authorize]屬性。

如何強制將登錄頁面作爲完整視圖返回?

回答

5

您可以擴展[Authorize]屬性,以便覆蓋HandleUnauthorizedRequest函數以將JsonResult返回給您的AJAX調用。

public class AuthorizeAjaxAttribute : 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 

      var referrer = filterContext.HttpContext.Request.UrlReferrer; 

      filterContext.Result = new JsonResult 
      { 
       JsonRequestBehavior = JsonRequestBehavior.AllowGet, 
       Data = new { redirectTo = FormsAuthentication.LoginUrl + 
          "?ReturnUrl=" + 
          referrer.LocalPath.Replace("/", "%2f") } 
      }; 
     } 
     else 
      base.HandleUnauthorizedRequest(filterContext); 
    } 
} 

創建一個JavaScript函數處理重定向:

<script type="text/javascript"> 
    function replaceStatus(result) { 
     // if redirectTo has a value, redirect to the link 
     if (result.redirectTo) { 
      window.location.href = result.redirectTo; 
     } 
     else { 
      // when the AJAX succeeds refresh the mydiv section 
      $('#mydiv').html(result); 
     } 
    }; 
</script> 

然後調用這個函數在Ajax.ActionLink

Ajax.ActionLink("Update Status", "GetStatus", 
       new AjaxOptions { OnSuccess="replaceStatus" }) 
+0

很不錯的解決方案的的onSuccess選項。如果AJAX操作也需要參數,我會建議用System.Web.HttpUtility.UrlEncode(referrer.PathAndQuery)替換語句referrer.LocalPath.Replace(「/」,「%2f」)。 – tranmq