The ASP.NET MVC 3 default template includes an AccountController class, an AccountModels class, and a set of views in the Account folder. Together, these items allow for managing ASP.NET security including register, logon, and change password. Absent from the template, however, is an good method or example of how to use the returnUrl parameter that exists inside the Logon method of the Account controller:

public ActionResult LogOn(LogOnModel model, string returnUrl)

You can pass a URL (or route) to the parameter and the Logon method will do its job, returning the user to the page once the user has completed the logon. However, if you examine the default view generated for LogOn you will notice no mention or use of this parameter. Instead, just a standard Html.BeginForm() call.

A common scenario is to pickup the page that sent the user to the LogOn view and then route the user back to that page once they have completed a successful logon. You can do so with a few simple (and very effective) lines of code.

First, declare a string variable at the top of the LogOn view. Set this variable’s value to the Request object’s UrlReferrer.PathAndQuery property.  Make sure you check this value for null first as it would not be set in the case a user goes directly to the Logon page. The following code is an example (using the Razor syntax):

@model MvcApplication2.Models.LogOnModel



    ViewBag.Title = "Log On";


    string retUrl = "";

    if (ViewContext.HttpContext.Request.UrlReferrer != null)


      retUrl =



The only other step is to modify the BeginForm call on the same view page. Here you make sure to pass the string variable that is set the the referring URL. The following code shows an example:

@using (Html.BeginForm("Logon", "Account",
  new { model = this.Model, returnUrl = retUrl }))

That’s it! The LogOn action method in the AccountController class takes care of the actual redirect.

Hope this is useful to everyone.