ReturnUrl in asp.net mvc for some reason is null

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 always zero, even if it was not null in HttpGet LogOn .

Why? How to fix it?

+4
source share
3 answers

You need returnUrl to be published with the form message.

Perhaps the purest solution is to add returnUrl as a property in the LogOnViewModel:

  public class LogOnViewModel { public string UserName { get; set; } public string Password { get; set; } public string ReturnUrl { get; set; } } 

Your get method will set this 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 save this value as a hidden field:

 @using (Html.BeginForm()) { @Html.HiddenFor(model => model.ReturnUrl) // rest of form code left out for demo purposes } 

Then your post method will have access to this 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); } 
+11
source

In the login window, add the ReturnUrl parameter to the form action. For instance:

 BeginForm("LogOn", "Account", new {ReturnUrl = Request.QueryString["ReturnUrl"]}) 

See davewasthere answer .

+2
source

When in the LogOn view, make sure that:

  • either url contains "returnUrl"
  • or is there a returnUrl field in the form
0
source

Source: https://habr.com/ru/post/1398575/


All Articles