在ASP.NET Core 2.2中,你可以使用RedirectToLogin方法来重定向到登录页。以下是一个解决方案的示例代码:
在Startup.cs文件的ConfigureServices方法中添加以下代码:
services.AddAuthentication(options =>
{
options.DefaultScheme = CookieAuthenticationDefaults.AuthenticationScheme;
options.DefaultChallengeScheme = OpenIdConnectDefaults.AuthenticationScheme;
})
.AddCookie(options =>
{
options.LoginPath = "/Account/Login"; // 设置登录页的路径
})
.AddOpenIdConnect(options =>
{
// 设置OpenID Connect的相关配置
});
在Startup.cs文件的Configure方法中添加以下代码:
app.UseAuthentication(); // 添加身份验证中间件
app.UseMvc(routes =>
{
routes.MapRoute(
name: "default",
template: "{controller=Home}/{action=Index}/{id?}");
});
在AccountController.cs文件中添加以下代码:
[AllowAnonymous]
public IActionResult Login(string returnUrl = null)
{
// 保存返回的URL
ViewData["ReturnUrl"] = returnUrl;
return View();
}
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public async Task Login(LoginViewModel model, string returnUrl = null)
{
ViewData["ReturnUrl"] = returnUrl;
if (ModelState.IsValid)
{
// 验证用户登录信息
// 如果验证成功,使用以下代码进行重定向
return RedirectToLocal(returnUrl);
}
// 如果验证失败,返回登录页
return View(model);
}
private IActionResult RedirectToLocal(string returnUrl)
{
if (Url.IsLocalUrl(returnUrl))
{
return Redirect(returnUrl);
}
else
{
return RedirectToAction(nameof(HomeController.Index), "Home");
}
}
请确保你已经安装了以下NuGet包:
以上代码示例了如何将登录页设置为/Account/Login,你可以根据你的实际需求进行更改。