public ActionResult LogOn(string returnUrl)
{
if (Request.IsAuthenticated)
{
return RedirectToAction(string.Empty, "home");
}
else
{
if (!string.IsNullOrWhiteSpace(returnUrl))
{
//http://localhost:666/en-us/account/logon?returnurl=%2fen-us%2fadminka
//..............
}
return View();
}
}
[HttpPost]
public ActionResult LogOn(LogOnViewModel model, string returnUrl)
{
if (ModelState.IsValid)
{
if (....)
{
//..............
if (Url.IsLocalUrl(returnUrl) && returnUrl.Length > 1 && returnUrl.StartsWith("/")
&& !returnUrl.StartsWith("//") && !returnUrl.StartsWith("/\\"))
return Redirect(returnUrl);
return RedirectToAction(string.Empty, "home");
}
else
{
//..............
}
}
return View(model);
}
In HttpPost LogOn
returnUrl
is always equals null, even if it was not null in HttpGet LogOn
.
Why? How do I fix it?
You need the returnUrl to be posted with the form post.
Probably the cleanest solution is to add returnUrl as a property to the LogOnViewModel:
public class LogOnViewModel
{
public string UserName { get; set; }
public string Password { get; set; }
public string ReturnUrl { get; set; }
}
Your get method would set that value:
[HttpGet]
public ActionResult LogOn(string returnUrl)
{
// code for already authenticated case left out for demo
var model = new LogOnViewModel { ReturnUrl = returnUrl };
return View(model);
}
}
In your form, you would persist that value as a hidden field:
@using (Html.BeginForm())
{
@Html.HiddenFor(model => model.ReturnUrl)
// rest of form code left out for demo purposes
}
Your post method would then have access to that value:
[HttpPost]
public ActionResult LogOn(LogOnViewModel model)
{
if (ModelState.IsValid)
{
if (....)
{ string returnUrl = model.ReturnUrl;
//..............
if (Url.IsLocalUrl(returnUrl) && returnUrl.Length > 1 && returnUrl.StartsWith("/")
&& !returnUrl.StartsWith("//") && !returnUrl.StartsWith("/\\"))
return Redirect(returnUrl);
return RedirectToAction(string.Empty, "home");
}
else
{
//..............
}
}
return View(model);
}
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