Redirect to last visited page (stored in a cookie)
In our MVC application we want the user, after he is logged in, to be redirected to the page he visted last in a previous session.
What is a good approach for achieving this?
I am thinking of an htt开发者_运维知识库pmodule-->begin request or via the global.asax
And at which point in the requestprocess should I put the logic to check whether the cookie exists and do the redirect? In the Application.init
?
Any advice would be really appreciated!
You could create a custom action filter that saves the currently requested URL to the cookie. Then check for the cookie value in your login action method and redirect if necessary.
In doing this you could decorate only the controllers and actions that you want that are potential entry points. e.g. not actions that return partial views etc.
That is correct, there is no event on click. However, there is a much simpler soluction, MVC handles form submits and redirects quite well. To store the last visited URL, you could use an action filter on your controller. Then to handle the redirect, create two Login functions. One handles the GET request, the other the POST request. In the POST request, after having verified authentication, retrieve the URL (or action) from the cookie and redirect the user.
It would be something like this:
[HttpGet]
public ActionResult Login()
{
return View();
}
[HttpPost]
public ActionResult Login(LoginViewModel model)
{
if (authenticated)
{
//get cookie information
HttpCookie cookie;
cookie = Request.Cookies["StoredURLFromLastSession"];
String StoredURLFromLastSession = cookie.Value;
//Choose one of these redirect methods
//returns to a hard coded URL
//return Redirect(StoredURLFromLastSession);
//redirects to a route (using routes created in global.asax
//return RedirectToRoute(StoredURLFromLastSession);
//redirects to a specific action/controller
//return RedirectToAction(StoredURLFromLastSession);
}
}
Hope this helps.
精彩评论