2011-11-29 90 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