services.AddAuthorizationCore(); // 添加身份验证服务
app.UseAuthorization(); // 启用身份验证中间件
@attribute [Authorize] // 将该页面设置为需要授权访问
例如,以下代码将使Index页面需要授权才能访问:
@page "/" @attribute [Authorize]
app.Use(async (context, next) => { if (!context.User.Identity.IsAuthenticated && context.Request.Path != "/Identity/Account/Login") { context.Response.Redirect("/Identity/Account/Login"); } else { await next(); } });
上述代码中,“/Identity/Account/Login”是登录页面的地址。如果用户未登录并访问了需要授权的页面,则会重定向到登录页面。
注意:如果还存在问题,可以尝试在浏览器控制台检查是否存在身份验证错误消息或JavaScript错误消息,以便更好地分析问题。