I am working on a ASP.Net core, MVC 6 application. I have an AppControler as my initial controller and if a user tries to go to an action that has an [Authorize] attribute, I redirect to my AuthController for the login, passing in the returnUrl for the return. Once authenticated, I use ... return RedirectToAction(returnUrl).
In debug, I can see that the returnUrl string is set to /App/Timesheets. However, in the browser address bar, it has an address of http://localhost:49940/Auth/%2FApp%2FTimeSheets . For some reason it is appending the controller name (Auth) in front of the returnUrl.
Here is my Login action in the AuthController
[HttpPost]
public async Task<ActionResult> Login(LoginViewModel vm, string returnUrl)
{
if (ModelState.IsValid)
{
var signInResult = await _signInManager.PasswordSignInAsync(vm.Username, vm.Password, true, false);
if (signInResult.Succeeded)
{
if (string.IsNullOrWhiteSpace(returnUrl))
{
return RedirectToAction("Timesheets", "App");
}
else
{
return RedirectToAction(returnUrl);
}
}
else
{
ModelState.AddModelError("", "Username or password incorrect");
}
}
return View();
}
I can manually enter http://localhost:49940/App/Timesheets in the browser address bar and get to the correct view. Also, if I add
returnUrl = String.Empty; //Test Only
before the line...
if (string.IsNullOrWhiteSpace(returnUrl))
to cause it to execute the line...
return RedirectToAction("Timesheets", "App");
The redirection works just fine. So it has something to do with passing in a string variable in the "/Controller/Action"
format that is the problem.
Any ideas?
When you have a full URL already, you should return a Redirect
. Currently you are doing a RedirectToAction
which will try to redirect to an action under the current controller (Auth).
if (signInResult.Succeeded)
{
if (string.IsNullOrWhiteSpace(returnUrl))
{
return RedirectToAction("Timesheets", "App");
}
else
{
return Redirect(returnUrl);
}
}
var redirect = RedirectToAction();
redirect.ActionName = "YourAction"; // or can use nameof("") like nameof(YourAction);
redirect.ControllerName= "YourCtrl"; // or can use nameof("") like nameof(YourCtrl);
return redirect;
I guess it just took writing out the problem description for me to see the problem.
I changed...
return RedirectToAction(returnUrl);
to...
return RedirectToAction(WebUtility.UrlEncode(returnUrl));
and now it is working properly.
:/
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.