在 ASP.Net Core 中,可以使用 Cookie 身份验证来验证用户的登录状态。如果用户已经登录但未经身份验证,可以使用以下代码示例来解决这个问题:
ConfigureServices 方法中添加 Cookie 身份验证服务:public void ConfigureServices(IServiceCollection services)
{
// ...
services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
.AddCookie(options =>
{
options.LoginPath = "/Account/Login";
options.AccessDeniedPath = "/Account/AccessDenied";
});
// ...
}
Configure 方法中启用身份验证中间件,并添加授权中间件:public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
// ...
app.UseAuthentication();
app.UseAuthorization();
// ...
}
[Authorize] 属性:[Authorize]
public class HomeController : Controller
{
// ...
}
这样,在用户已经登录但未经身份验证时,访问需要身份验证的页面或操作方法时,用户将被重定向到登录页面。
注意:此示例假设你已经创建了登录页面和访问被拒绝页面。你可以根据自己的需求调整登录路径和访问被拒绝路径。