I have an AccountController for authorization with Asp.Net Core Identity. If successful, I make a RedirectToAction and want to redirect the user to "returnUrl", but the redirection does not work correctly.
When the application opens, I am redirected to the authorization page (this is correct) and the URL looks like this:
https://localhost:7008/Account/Login?ReturnUrl=/
or if I requested an administration page
https://localhost:7008/Account/Login?ReturnUrl=/Admin
After successful authorization, I get a 404 error, since RedirectToAction eventually generates such URLs:
https://localhost:7008/Account//
https://localhost:7008/Account//Admin
As if the Account controller is still present in the URL!
Here are the controller methods:
[AllowAnonymous]
public IActionResult Login(string returnUrl) {
ViewBag.returnUrl = returnUrl;
return View();
}
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Login(LoginModel model, string returnUrl) {
if (ModelState.IsValid) {
var user = await _userManager.FindByNameAsync(model.Login);
if (user != null) {
await _signInManager.SignOutAsync();
var result = await _signInManager.PasswordSignInAsync(user, model.Password, false, false);
if (result.Succeeded) {
return RedirectToAction(returnUrl ?? "/");
}
}
ModelState.AddModelError(nameof(LoginModel.Login), "Invalid login or password!");
}
return View(model);
}
Program.cs:
app.MapControllerRoute(
name: "default",
pattern: "{controller=Home}/{action=Index}/{id?}");
CodePudding user response:
Your returnUrl
parameter contains not an action name but just a relative url path.
Try to use Redirect(string url)
method instead of RedirectToAction(string actionName)
.
CodePudding user response:
RedirectToAction
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. In this case, the browser receives the redirect notification and make a new request for the specified action.
Redirect
method is used to redirect to specified URL
instead of rendering HTML. In this case, the browser receives the redirect notification and make a new request for the specified URL.
You use RedirectToAction("/"), so application is looking for action named "/". If you would use Redirect("/") instead, you would get redirected to main page.
RedirectToAction("something"):
https://localhost:7008/Account/something
Redirect("something"):
https://localhost:7008/something