ASP.NET MVC Ajax post to Action requiring authentication returns login view when user session has timed out

asp.net-mvcasp.net-mvc-ajax

I am using the Ajax.BeginForm to create a form the will do an ajax postback to a certain controller action and then the response view is inserted into the UpdateTargetId.

using (Ajax.BeginForm("Save", null,
        new { userId = Model.UserId },
        new AjaxOptions { UpdateTargetId = "UserForm" },
        new { name = "SaveForm", id = "SaveForm" }))
   {
    [HTML SAVE BUTTON]
   }

Everything works great except when the Users session has timed out and then they are redirected back to the login page. The login page then gets returned from the Ajax call because of the Authorize attribute and the html gets loaded into the UpdateTargetId and therefore I end up with the login page html within the user profile page (at the Target Id). My controller action looks like this:

[Authorize]
public ActionResult Save(Int32 UserId)
{
    //code to save user
    return View("UserInfoControl", m);

}

How can I solve this problem?

UPDATE (2011-10-20):
Found this post from Phil Haack about this exact issue – http://haacked.com/archive/2011/10/04/prevent-forms-authentication-login-page-redirect-when-you-donrsquot-want.aspx. I have not gotten a chance to digest or implement his solution yet.

Best Answer

I think that you can handle the authorization issue from inside the action. First remove [Authorize], the use this code:

public ActionResult Save(Int32 UserId)
{
    if (!User.Identity.IsAuthenticated) 
    { 
        throw new Exception();
    }
    //code to save user
    return View("UserInfoControl", m);

}

Then you can put a OnFailure condition in your AjaxOptions and redirect your page or something.