在ASP .NET Core 5.0 Razor Pages Web应用程序中使用ASP .NET Core Identity时,需要进行适当的配置和编写代码。具体步骤如下:
Step 1:安装Identity包
在项目中安装Microsoft.AspNetCore.Identity.EntityFrameworkCore包,通过NuGet软件包管理器来完成安装。
Step 2:创建Identity模型
可以使用Visual Studio中的Identity Scaffolder来创建ASP .NET Core Identity的默认模型,也可以根据需要自定义模型。
使用Identity模型需要在应用程序中添加一个DbContext,以及在Startup文件的ConfigureServices方法中注入Identity依赖项。
Step 3:配置Identity
在Startup文件中,需要配置Identity服务并启用Cookie认证。具体代码示例如下:
services.AddIdentity()
.AddEntityFrameworkStores()
.AddDefaultTokenProviders();
services.Configure(options =>
{
//Password settings
options.Password.RequireDigit = true;
options.Password.RequiredLength = 8;
options.Password.RequireNonAlphanumeric = false;
options.Password.RequireUppercase = true;
options.Password.RequireLowercase = true;
//Lockout settings
options.Lockout.DefaultLockoutTimeSpan = TimeSpan.FromMinutes(30);
options.Lockout.MaxFailedAccessAttempts = 10;
options.Lockout.AllowedForNewUsers = true;
//User settings
options.User.RequireUniqueEmail = true;
});
通过以上代码,可以实现配置Identity服务的目的。
Step 4:添加用户认证
在Razor Pages中,可以使用[Authorize]属性来标记需要进行用户认证的页面或Controller/Action。例如,代码示例如下:
[Authorize]
public class HomeController : Controller
{
public IActionResult Index()
{
return View();
}
}
当用户未经认证就尝试访问该页面时,系统会自动跳转至登录页面。
Step 5:添加角色基础