You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在ASP.NET Core 7的Telerik Blazor项目中为ASP.NET Core Identity添加自定义字段

在ASP.NET Core 7 + Telerik Blazor项目中为Identity添加自定义用户字段

1. 扩展IdentityUser实体

创建自定义用户类继承IdentityUser,添加所需的自定义字段:

using Microsoft.AspNetCore.Identity;

public class ApplicationUser : IdentityUser
{
    public string? FirstName { get; set; }
    public string? LastName { get; set; }
    public string? Address { get; set; }
    public string? PostalCode { get; set; }
}

更新Program.cs中的Identity服务配置,替换默认用户类型为自定义的ApplicationUser:

builder.Services.AddDefaultIdentity<ApplicationUser>(options => options.SignIn.RequireConfirmedAccount = true)
    .AddEntityFrameworkStores<ApplicationDbContext>();

确保数据库上下文继承IdentityDbContext<ApplicationUser>:

using Microsoft.AspNetCore.Identity.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore;

public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
{
    public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options)
        : base(options)
    {
    }
}

2. 生成并应用数据库迁移

在终端或Package Manager Console执行以下命令,更新数据库结构:

Add-Migration AddCustomUserFields
Update-Database

3. 修改注册ViewModel

更新注册视图模型,添加对应自定义字段用于接收前端输入:

public class RegisterViewModel
{
    [Required]
    [EmailAddress]
    public string Email { get; set; } = string.Empty;

    [Required]
    [DataType(DataType.Password)]
    public string Password { get; set; } = string.Empty;

    [DataType(DataType.Password)]
    [Compare("Password", ErrorMessage = "密码和确认密码不匹配。")]
    public string ConfirmPassword { get; set; } = string.Empty;

    [Required]
    public string FirstName { get; set; } = string.Empty;

    [Required]
    public string LastName { get; set; } = string.Empty;

    public string? Address { get; set; }

    public string? PostalCode { get; set; }
}

4. 更新Telerik Blazor注册页面UI

在注册组件中添加Telerik输入组件,收集自定义字段值,并完善注册逻辑:

@page "/register"
@inject UserManager<ApplicationUser> UserManager
@inject SignInManager<ApplicationUser> SignInManager
@inject NavigationManager NavigationManager

<EditForm Model="@RegisterModel" OnValidSubmit="@HandleRegister">
    <DataAnnotationsValidator />
    <ValidationSummary />

    <TelerikTextBox @bind-Value="@RegisterModel.Email" Label="邮箱" Placeholder="输入邮箱" />
    <TelerikTextBox @bind-Value="@RegisterModel.Password" Label="密码" Placeholder="输入密码" Type="InputType.Password" />
    <TelerikTextBox @bind-Value="@RegisterModel.ConfirmPassword" Label="确认密码" Placeholder="确认密码" Type="InputType.Password" />

    <!-- 自定义字段输入区域 -->
    <TelerikTextBox @bind-Value="@RegisterModel.FirstName" Label="名字" Placeholder="输入名字" />
    <TelerikTextBox @bind-Value="@RegisterModel.LastName" Label="姓氏" Placeholder="输入姓氏" />
    <TelerikTextBox @bind-Value="@RegisterModel.Address" Label="地址" Placeholder="输入地址" />
    <TelerikTextBox @bind-Value="@RegisterModel.PostalCode" Label="邮政编码" Placeholder="输入邮政编码" />

    <TelerikButton ButtonType="ButtonType.Submit" ThemeColor="Primary">注册</TelerikButton>
</EditForm>

@code {
    private RegisterViewModel RegisterModel = new();

    private async Task HandleRegister()
    {
        var user = new ApplicationUser
        {
            UserName = RegisterModel.Email,
            Email = RegisterModel.Email,
            FirstName = RegisterModel.FirstName,
            LastName = RegisterModel.LastName,
            Address = RegisterModel.Address,
            PostalCode = RegisterModel.PostalCode
        };

        var result = await UserManager.CreateAsync(user, RegisterModel.Password);
        if (result.Succeeded)
        {
            await SignInManager.SignInAsync(user, isPersistent: false);
            NavigationManager.NavigateTo("/");
        }
        else
        {
            foreach (var error in result.Errors)
            {
                EditContext.AddModelError(string.Empty, error.Description);
            }
        }
    }
}

5. 展示自定义用户信息(可选)

在个人资料页通过UserManager获取当前用户的自定义字段并展示:

@page "/profile"
@inject UserManager<ApplicationUser> UserManager
@inject AuthenticationStateProvider AuthenticationStateProvider

<h3>个人资料</h3>

@if (CurrentUser != null)
{
    <p>名字: @CurrentUser.FirstName</p>
    <p>姓氏: @CurrentUser.LastName</p>
    <p>地址: @CurrentUser.Address</p>
    <p>邮政编码: @CurrentUser.PostalCode</p>
}

@code {
    private ApplicationUser? CurrentUser;

    protected override async Task OnInitializedAsync()
    {
        var authState = await AuthenticationStateProvider.GetAuthenticationStateAsync();
        var user = authState.User;

        if (user.Identity?.IsAuthenticated == true)
        {
            CurrentUser = await UserManager.GetUserAsync(user);
        }
    }
}

内容的提问来源于stack exchange,提问作者Mehdi Mehdi Pour

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.20 07:48:21