要解决ASP.NET Core 2.2 MVC在登录后重定向的问题,你可以按照以下步骤进行操作:
services.AddAuthentication()
.AddCookie(options =>
{
options.LoginPath = "/Account/Login"; // 设置登录页面的路径
options.LogoutPath = "/Account/Logout"; // 设置退出登录的路径
});
services.AddAuthorization();
SignInManager来验证用户的凭据,并在成功登录后重定向到指定的URL。在AccountController.cs文件中的Login方法中,添加以下代码:[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public async Task Login(LoginViewModel model, string returnUrl = null)
{
ViewData["ReturnUrl"] = returnUrl;
if (ModelState.IsValid)
{
var result = await _signInManager.PasswordSignInAsync(model.Email, model.Password, model.RememberMe, lockoutOnFailure: false);
if (result.Succeeded)
{
return RedirectToLocal(returnUrl); // 重定向到指定的URL
}
// 如果登录失败,显示错误信息
ModelState.AddModelError(string.Empty, "Invalid login attempt.");
return View(model);
}
return View(model);
}
private IActionResult RedirectToLocal(string returnUrl)
{
if (Url.IsLocalUrl(returnUrl))
{
return Redirect(returnUrl);
}
else
{
return RedirectToAction(nameof(HomeController.Index), "Home");
}
}
[Authorize]特性,以确保只有登录用户可以访问。例如:[Authorize]
public class MyController : Controller
{
// ...
}
通过以上步骤,你应该可以解决ASP.NET Core 2.2 MVC在登录后重定向的问题,并根据需要进行自定义重定向。