Tag: BeginForm

.Net MVC 3 Logon does not redirect out the box–quick fix!

It seems that the templates for MVC 3 razor are not quite complete. If you attempt to browse to a page where authentication is required, then you will be redirect to the Logon page with a ReturnUrl query string.

Something like:

http://mysite.com/Account/LogOn?ReturnUrl=%2fThePageIWant

That’s great except, out the box, the Logon page does not make use of this and the destination page is not redirected to after a successful login. The fix is easy.

Add the returnUrl route value into the Html.BeginForm method as shown below.

Html.BeginForm("LogOn", "Account", new { returnUrl = Request.QueryString["ReturnUrl"] })

You should already have some code in the controller that does some sanity checking on the returnUrl before doing the redirect. Somthing like:

if (Url.IsLocalUrl(returnUrl) && returnUrl.Length > 1 && returnUrl.StartsWith("/")
       && !returnUrl.StartsWith("//") && !returnUrl.StartsWith("/\\"))
{
    return Redirect(returnUrl);
}

Make sure this is after the SetAuthCookie line!