views:

238

answers:

1

Hi Guys

I'm trying to use the following code to log users in:

$("form").submit(function(event)
{
    $.ajax({
        type: "POST",
        url: $(this).attr("action"),
        data: $(this).serialize(),
        complete: function(XMLHttpRequest, textStatus)
        {
            if (XMLHttpRequest.status === 302)
            {
                // if they've successfully logged in, I redirect to their page
                window.location = XMLHttpRequest.getResponseHeader("Location");
            }
        }
    });

    return false;
});

with the following code on the server to handle the post:

[AcceptVerbs(HttpVerbs.Post)]
public  ActionResult LogOn(MyUser user)
{
    if (ValidateLogOn(user.UserName, user.Password))
    {
        if (Request.QueryString["ReturnUrl"] != null)
        {
            return Redirect(Request.QueryString["ReturnUrl"]);
        }
        else
        {
            return RedirectToRoute("Default");
        }
    }
}

I thought both 'Redirect' Action Results were supposed to issue 302s but the XMLHttpRequest.status value is always 200. Is there something I'm doing wrong?

EDIT: This is what eventually worked

$("form").submit(function(event)
{
    $.ajax({
        type: "POST",
        url: $(this).attr("action"),
        data: $(this).serialize(),
        complete: function(xhr, textStatus)
        {
            var dataType = xhr.getResponseHeader("Content-Type");

            if (dataType.indexOf("json") > -1)
            {
                window.location = JSON.parse(xhr.responseText).returnUrl;
            }

            if (dataType.indexOf("html") > -1)
            {
                $('#main').html(xhr.responseText);
            }
        }
    });            
    return false;
});    

with the following on the server:

[AcceptVerbs(HttpVerbs.Post)]
public ActionResult LogOn(MyUser user, string returnUrl)
{
    if (!ValidateLogOn(user.UserName, user.Password))
    {
        return PartialView();
    }
    else
    {
        user = (MyUser)Session["CurrentUser"];
        if (user.IsPublic)
        {
            return Json(new { returnUrl = Url.RouteUrl("PublicRoute") });
        }
        else
        {
            if (!string.IsNullOrEmpty(returnUrl))
            {
                return Json(new { returnUrl = returnUrl.ToLower() });
            }
            else
            {
                return Json(new { returnUrl = Url.RouteUrl("AdminRoute") });
            }
        }
    }
}

Thanks

Dave

A: 

Your browser is automatically following the redirect and requesting the redirect page, which is then returning 200. Run a proxy (like Fiddler or Charles) to see what I mean.

I'd recommend returning a 200 status, but use a JSON object to specify that you want to redirect the user.

Additionally, this answer recommends using status 278 (apparently an unused status code, which sounds dangerous to me) in this scenario.

Richard Szalay