I have a link in my razor view like this:
<a href="Home/Login?ReturnUrl=Disputes/Index"> disputes</a>
Inside my login's action method, I am using this:
public ActionResult Login(string returnUrl) { if (string.IsNullOrEmpty(returnUrl) && Request.UrlReferrer != null) returnUrl = Server.UrlEncode(Request.UrlReferrer.PathAndQuery); if (Url.IsLocalUrl(returnUrl) && !string.IsNullOrEmpty(returnUrl)) { ViewBag.ReturnURL = returnUrl; } return View(); }
In view I am using this:
@Html.Hidden("returnUrl",@Request.QueryString)
Then in post action method:
public ActionResult LogOn(LogOnModel model, string returnUrl) { if (ModelState.IsValid) { if (membershipService.ValidateUser(model.UserName, model.Password, model.Type)) { formsAuthenticationService.SignIn(model.UserName, model.RememberMe); SetUserInfo(model.UserName); string decodedUrl = ""; if (!string.IsNullOrEmpty(returnUrl)) decodedUrl = Server.UrlDecode(returnUrl); if (Url.IsLocalUrl(decodedUrl)) return Redirect(decodedUrl); else return Redirect("Home", Index); } } }
It is redirecting to:/Disputes/Index
but it should go to myApp/Disputes/Index
where the url with query string is like this. /myApp/Home/Login?ReturnUrl=/Disputes/Index
How can I solve this issue?
The most common ways to implement redirection logic after login are: using HTTP Referer header. saving the original request in the session. appending original URL to the redirected login URL.
You can apply this filter to the routes that need authentication. Route::filter('auth', function() { if (Auth::guest()) { return Redirect::guest('login'); } }); What this method basically does it's to store the page you were trying to visit and it is redirects you to the login page. return Redirect::intended();
I use a combination of the above suggestion and Request.UrlReferrer
to get the previous location:
public ActionResult LogOn(string returnUrl) { //So that the user can be referred back to where they were when they click logon if (string.IsNullOrEmpty(returnUrl) && Request.UrlReferrer != null) returnUrl = Server.UrlEncode(Request.UrlReferrer.PathAndQuery); if (Url.IsLocalUrl(returnUrl) && !string.IsNullOrEmpty(returnUrl)) { ViewBag.ReturnURL = returnUrl; } return View(); }
This way I don't have to put the location in the ActionLink
.
I populate a hidden field in the login page using the ViewBag.ReturnURL
. Then in the Login HTTPPost ActionResult
I redirect the user to the location in the hidden field (if there is one):
[HttpPost] public ActionResult LogOn(LogOnModel model, string returnUrl) { //returnURL needs to be decoded string decodedUrl = ""; if (!string.IsNullOrEmpty(returnUrl)) decodedUrl = Server.UrlDecode(returnUrl); //Login logic... if (Url.IsLocalUrl(decodedUrl)) { return Redirect(decodedUrl); } else { return RedirectToAction("Index", "Home"); } }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With