开发者

ASP.NET MVC 2 AJAX Calls when login token has expired

When a users login token has expired (ie. they have been logged out) on a page that has AJAX enabled content, if they select a AJAX link on the page it will appear to complete succesfully. However this is not the case. The content that was returned to the page is the Login Redirection. Is there any way to have the AJAX call redirect to the login page if the user is logged out? From what I can see the obvious way would be to add code to the Control开发者_开发百科ler which would pass an error to the AJAX caller so it would handle the users state however because this is forms authentication the authentication happens prior to the controller being called.

Any thoughts on how to handle this? Thanks in advance!


you can customize [Authorize] attribute like this

public class CustomAuthorize : AuthorizeAttribute
{
    protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext)
    {
        //you can change to any controller or html page.
        //filterContext.Result = new RedirectResult("/Account/Login");
        if (filterContext.HttpContext.Request.IsAjaxRequest())
        {
            string destinationUrl = UrlHelper.GenerateContentUrl(FormsAuthentication.LoginUrl, filterContext.HttpContext);
            filterContext.Result = new JavaScriptResult()
            {
                Script = "window.location = '" + destinationUrl + "';"
            };
        }
        else
        {
            base.HandleUnauthorizedRequest(filterContext);
        }
    }
}

you can use this attribute same like you use [Authorize] attribute on controller or perticular action.

[CustomAuthorize]
public class UserController : Controller
{
   // your actions here
}

or

public class UserController : Controller
{
   [CustomAuthorize]
   Public ActionResult Indes()
   {   
        // your code here
   }
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜