Simple enough, it would seem, but it turns out not to be - mainly due to the fact that the View can\'t possibly know which way through Model and Controller you got there. Regard
You can use Page.Request.Url
to get the route that resulted in the currently rendered view.
Though that's more of a cosmetic detail, you might want to unify the requests that came through the '/' and '/default.aspx' routes and always return to the '/' route. I have a helper property in my master page that does exactly that.
protected Uri RouteUrl
{
get
{
if (Page.Request.Url.AbsolutePath.StartsWith("/default.aspx", StringComparison.OrdinalIgnoreCase))
{
return new Uri(Request.Url, new Uri(Response.ApplyAppPathModifier("~/")));
}
return Page.Request.Url;
}
}
The solution is to use HttpContext.Current.Request.RawUrl like this:
<%= Html.ActionLink("log on", "LogIn", new { controller = "User", returnUrl = HttpContext.Current.Request.RawUrl }) %>
Or with an extension method from MVC futures (Microsoft.Web.Mvc.dll):
<%= Html.ActionLink<AccountController>(c => c.LogOn("name", "password", false, HttpContext.Current.Request.RawUrl), "login here")%>
ActionController is the default one in mvc but just add returnUrl to your own.
One way would be to build the links that send the user to the login form, with returnUrl=/PageToReturnTo (<a href="/Account/Login/?returnUrl=/Product/10">Login</a>
for example). You'd want to write it so the return url was constructed from your routes though, manually writing those links on every page could be cumbersome.
The default login action in MVC has the returnUrl functionality already built. Just need to pass it a value and it will do the rest. Here's a copy'n paste of the method signature from a fresh project.
public ActionResult Login(string username, string password, bool rememberMe, string returnUrl)
Hope that helps ya!
I don't know about ASPX, but there are a couple of problems we encountered building this:
When the user gets their password wrong, and loops-round the Login page to have another go, the Target must still be preserved.
We also decided to preserve POST variables to a page that then required the just-in-time login