In the usual AccountController
in my MVC3 app, if returnUrl
is set (in my case, I set it manually), it will call Redirect(returnUrl)
.
Assume my return URL is /Admin/HealthCheck
(which it really is). When I'm debugging, I get a URL like http://localhost:3279/Admin/HealthCheck
from the redirect call.
Then, I deployed my app to http://localhost/Test
. In this case, Redirect(returnUrl)
redirects me to http://localhost/Admin/HealthCheck
and not the expected http://localhost/Test/Admin/HealthCheck
.
What's going on here? How do I fix this (if it is fixable)?
Below is a snippet from the (standard) MVC3 AccountController; you can see where I get the return URL from the query string (eg. http://localhost/Test/LogOn?ReturnUrl=/Admin/HealthCheck
, albeit URL encoded).
[HttpPost]
public ActionResult LogOn(LogOnModel model, string returnUrl)
{
if (ModelState.IsValid)
{
if (Membership.ValidateUser(model.UserName, model.Password))
{
returnUrl = Request.Params["ReturnUrl"];
FormsAuthentication.SetAuthCookie(model.UserName, model.RememberMe);
if (Url.IsLocalUrl(returnUrl) && returnUrl.Length > 1 && returnUrl.StartsWith("/")
&& !returnUrl.StartsWith("//") && !returnUrl.StartsWith("/\\"))
{
return Redirect(returnUrl);
}
else
{
return RedirectToAction("Index", "Home");
}
}
else
{
ModelState.AddModelError("", "The user name or password provided is incorrect.");
}
}
The RedirectToAction() Method This method is used to redirect to specified action instead of rendering the HTML. In this case, the browser receives the redirect notification and make a new request for the specified action.
RedirectToAction(String) Redirects to the specified action using the action name. RedirectToAction(String, Object) Redirects to the specified action using the action name and route values.
Use RedirectToActionResult in ASP.NET Core MVCThis action result can be used to redirect to the specified action and controller. If no controller is specified it redirects to the specified action within the current controller.
(in my case, I set it manually)
You haven't actually shown how this manual setting happens, but if you have hardcoded an url such as /Admin/HealthCheck
instead of using an url helper to generate this url such as Url.Action("HealthCheck", "Admin")
don't expect miracles to happen.
Your LogOn
is fine. It does what it is supposed to do => it redirects to the url that is passed as argument. Your problem lies in the way you are setting this url.
Conclusion: in an ASP.NET MVC application always use url helpers when dealing with urls. Never hardcode them.
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