Asp.Net Core Identity RedirectToAction



我有一个用于Asp授权的AccountController。网络核心身份。如果成功,我创建一个RedirectToAction,并希望将用户重定向到"returnUrl",但是重定向不能正常工作。

当应用程序打开时,我被重定向到授权页面(这是正确的),URL看起来像这样:
https://localhost:7008/Account/Login?ReturnUrl=%2F

或者如果我请求管理页面

https://localhost:7008/Account/Login?ReturnUrl=%2FAdmin

成功授权后,我得到一个404错误,因为RedirectToAction最终生成这样的url:

https://localhost:7008/Account/%2F
https://localhost:7008/Account/%2FAdmin

就好像Account控制器仍然存在于URL中一样!

以下是控制器方法:

[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?}");

RedirectToAction方法用于重定向到指定的action,而不是呈现HTML。在这种情况下,浏览器接收重定向通知并为指定的操作发出新的请求。在这种情况下,浏览器接收重定向通知,并为指定的操作发出新的请求。

Redirect方法用于重定向到指定的URL,而不是呈现HTML。在这种情况下,浏览器接收到重定向通知,并对指定的URL发出新的请求。

您使用了RedirectToAction("/"),所以应用程序正在寻找名为"/"的操作。如果你想使用重定向("/")相反,你会重定向到主页。

RedirectToAction("something":

https://localhost:7008/Account/something

重定向("something":

https://localhost:7008/something

https://www.dotnettricks.com/learn/mvc/return-view-vs-return-redirecttoaction-vs-return-redirect-vs-return-redirecttoroute

我不知道你想达到什么目的,所以我建议以下其中一种:

return Redirect(returnUrl);
return Redirect("ControllerName/" + returnUrl);
return RedirectToAction("ActionName", new { returnUrl = returnUrl });
return RedirectToAction("ActionName", "ControllerName", new { returnUrl = returnUrl });

您的returnUrl参数包含的不是操作名称,而是相对url路径。

尝试使用Redirect(string url)方法代替RedirectToAction(string actionName)

最新更新