📜  在没有脚手架的情况下创建自定义注册 blazor 页面 (1)

📅  最后修改于: 2023-12-03 14:51:30.137000             🧑  作者: Mango

在没有脚手架的情况下创建自定义注册 Blazor 页面

Blazor 是 .NET 运行时的客户端实现,它使用 C# 代替 JavaScript 和 WebAssembly,可以让开发人员通过 C# 编写 Web 应用程序。为了更好地扩展应用程序并充分利用 Blazor 的强大功能,我们需要自定义页面并启用注册流程。

在本文中,我们将介绍如何在没有脚手架的情况下创建自定义注册 Blazor 页面。以下是相应代码。

步骤 1:创建组件和模型

我们需要创建一个包含注册页面和注册模型的组件。

注册页面
@page “/register”
@inject NavigationManager NavigationManager
@inject IAuthService authService

<h1>Register New User</h1>

<EditForm Model=”_model”>
    <DataAnnotationsValidator />
    <ValidationSummary />

    <div class=”form-group”>
        <label for=”Email”>Email</label>
        <InputText class=”form-control” id=”Email” @bind-Value=”_model.Email” />
    </div>

    <div class=”form-group”>
        <label for=”Password”>Password</label>
        <InputText class=”form-control” type=”password” id=”Password” @bind-Value=”_model.Password” />
    </div>

    <div class=”form-group”>
        <label for=”ConfirmPassword”>Confirm Password</label>
        <InputText class=”form-control” type=”password” id=”ConfirmPassword” @bind-Value=”_model.ConfirmPassword” />
    </div>

    <button type=”submit” class=”btn btn-primary”>Register</button>
</EditForm>
注册模型
public class RegisterModel
{
    [Required]
    [EmailAddress]
    public string Email { get; set; }

    [Required]
    [MinLength(6)]
    public string Password { get; set; }

    [Compare(“Password”)]
    public string ConfirmPassword { get; set; }
}
步骤 2:创建服务

我们需要创建一个身份验证服务,以便对注册的用户进行身份验证。以下是相应代码。

public interface IAuthService
{
    Task<IdentityResult> Register(RegisterModel model);
}

public class AuthService : IAuthService
{
    private readonly UserManager<IdentityUser> _userManager;

    public AuthService(UserManager<IdentityUser> userManager)
    {
        _userManager = userManager;
    }

    public async Task<IdentityResult> Register(RegisterModel model)
    {
        var user = new IdentityUser { UserName = model.Email, Email = model.Email };
        var result = await _userManager.CreateAsync(user, model.Password);

        return result;
    }
}
步骤 3:在应用程序中启用路由

要使应用程序能够路由到我们的注册页面,我们需要在应用程序中启用路由。

以下是相应代码。

public void ConfigureServices(IServiceCollection services)
{
    // Add routing services to the container
    services.AddRouting();

    // Add authentication services to the container    
    services.AddAuthentication(options =>
    {
        options.DefaultScheme = JwtBearerDefaults.AuthenticationScheme;
        options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
    })
    .AddJwtBearer(jwtOptions =>
    {
        jwtOptions.Authority = Configuration["Jwt:Authority"];
        jwtOptions.Audience = Configuration["Jwt:Audience"];
        jwtOptions.IncludeErrorDetails = true;
    });

    // Add authorization services to the container
    services.AddAuthorization();

    // Add Identity services to the container
    services.AddIdentity<IdentityUser, IdentityRole>(options => options.SignIn.RequireConfirmedAccount = true)
        .AddEntityFrameworkStores<ApplicationDbContext>()
        .AddDefaultTokenProviders();

    // Add our custom auth service to the container
    services.AddScoped<IAuthService, AuthService>();
}

public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
    // Enable routing middleware
    app.UseRouting();

    // Enable authentication middleware
    app.UseAuthentication();

    // Enable authorization middleware
    app.UseAuthorization();

    app.UseEndpoints(endpoints =>
    {
        endpoints.MapControllers();
        endpoints.MapRazorPages();
    });
}
步骤 4:测试应用程序

使用上面提供的代码,我们已经创建了一个自定义注册 Blazor 页面。现在,您可以测试应用程序以确保一切正常。

为此,请在浏览器中打开应用程序并转到 /register 。您应该看到注册页面。