Categories
Uncategorized

Using Return Url in ASP.NET MVC 3

Implementing returnUrl in ASP.NET MVC is easy and pretty straight forward. Below are the steps you need to follow to ensure that it works correctly.

Step 1 : Setup the loginUrl to the appropriate action. In my example I have set it to “LogOn” action of the Account Controller.
[sourcecode language=”xml”]
<authentication mode=”Forms”>
 <forms loginUrl=”~/Account/LogOn” timeout=”2880″ />
</authentication>
[/sourcecode]

Step 2 : Setting up controller, 
[sourcecode language=”csharp”]
public ActionResult LogOn(string returnUrl)
{
 return View();
}

[HttpPost]
public ActionResult LogOn(LogOnModel model, string returnUrl)
{
 if (ModelState.IsValid)
 {
 if (ValidateUser(model.UserName, model.Password))
 {
 return SignIn(model, returnUrl);
 }
 else
 {
 ModelState.AddModelError(“”, “The user name or password provided is incorrect.”);
 }
 }
 
 return View(model);
}

private ActionResult SignIn(LogOnModel model, string returnUrl)
{
 Signin(model);

if (Url.IsLocalUrl(returnUrl) && returnUrl.Length > 1 && returnUrl.StartsWith(“/”) && !returnUrl.StartsWith(“//”) && !returnUrl.StartsWith(“/\”))
 {
 return Redirect(returnUrl);
 }
 else
 {
 return RedirectToAction(“Index”, “Home”);
 }
}
[/sourcecode]

Step 3 : Posting the return Url from the form to the Logon Controller.
[sourcecode language=”csharp”]
@using (Html.BeginForm(“LogOn”,”Account”,new { returnurl = Request.QueryString[“returnurl”] })) {
}
[/sourcecode]

Hope this helps 🙂