Blazor(服务器端)身份验证和控制器页面可以使用ASP.NET Core Identity进行身份验证和创建控制器页面。以下是创建Blazor身份验证和控制器页面的步骤:
创建一个新的ASP.NET Core Web应用程序,并选择Blazor服务器端模板。
在应用程序中使用以下命令安装Microsoft.AspNetCore.Identity包:
Install-Package Microsoft.AspNetCore.Identity
在Startup.cs文件中,使用以下代码更新ConfigureServices方法,以添加身份验证和授权配置:
services.AddIdentity(options =>
{
options.Password.RequireDigit = true;
options.Password.RequireLowercase = true;
options.Password.RequireUppercase = true;
options.Password.RequireNonAlphanumeric = false;
options.Password.RequiredLength = 8;
})
.AddEntityFrameworkStores();
services.AddAuthorization();
在App.razor文件中,添加以下代码,以便在应用程序中使用身份验证:
Sorry, there's nothing at this address.
在要保护的页面上添加[Authorize]属性,以强制要求用户登录才能访问页面。
[Authorize]
public class PrivatePage : ComponentBase
{
// Page content
}
创建控制器页面,如以下示例:
@page "/samplepage"
@inject UserManager UserManager
Hello, @UserManager.GetUserName(User)
在此示例中,我们注入了