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

Blazor Server应用中Microsoft.AspNetCore.Identity 2.2.0替代包及用户数据自定义咨询

Microsoft.AspNetCore.Identity 2.2.0替代方案及Blazor Server用户自定义指南

一、替代包说明

Microsoft.AspNetCore.Identity 2.2.0是适配旧版ASP.NET Core 2.2的包,目前已随.NET Core 2.2生命周期结束被弃用。你只需安装与当前Blazor Server项目所使用的.NET版本对齐的最新稳定版Microsoft.AspNetCore.Identity包即可。

比如你的项目基于.NET 7,就安装7.x版本;基于.NET 8则安装8.x版本。新版本已整合到ASP.NET Core框架生态中,完全兼容Blazor Server,且包含所有旧版的核心功能,同时修复了安全漏洞、优化了性能。

二、自定义登录用户数据的实现方案

1. 自定义用户实体类

继承IdentityUser,添加你需要的自定义字段,示例如下:

public class ApplicationUser : IdentityUser
{
    // 自定义字段示例
    public string FullName { get; set; }
    public DateTime DateOfBirth { get; set; }
    public string AvatarUrl { get; set; }
}

2. 更新数据库上下文

让项目的DbContext继承IdentityDbContext<ApplicationUser>,关联自定义用户类:

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

3. 配置服务注册

在Program.cs中,注册Identity服务时指定自定义用户类型:

builder.Services.AddDefaultIdentity<ApplicationUser>(options => 
{
    options.SignIn.RequireConfirmedAccount = true;
    // 可根据需求配置其他Identity选项,比如密码复杂度、锁定规则等
})
.AddEntityFrameworkStores<ApplicationDbContext>();

4. 更新数据库结构

通过EF Core迁移命令,将自定义字段同步到数据库:

# 添加迁移文件
Add-Migration AddCustomUserProperties
# 执行迁移,更新数据库
Update-Database

5. 在Blazor组件中获取自定义用户数据

通过UserManager<ApplicationUser>注入,获取当前登录用户的自定义信息:

@inject UserManager<ApplicationUser> UserManager
@inject AuthenticationStateProvider AuthenticationStateProvider

<div>
    @if (currentUser != null)
    {
        <p>用户名:@currentUser.UserName</p>
        <p>真实姓名:@currentUser.FullName</p>
        <p>生日:@currentUser.DateOfBirth.ToShortDateString()</p>
    }
</div>

@code {
    private ApplicationUser currentUser;

    protected override async Task OnInitializedAsync()
    {
        var authState = await AuthenticationStateProvider.GetAuthenticationStateAsync();
        var user = authState.User;
        if (user.Identity.IsAuthenticated)
        {
            currentUser = await UserManager.GetUserAsync(user);
        }
    }
}

额外说明

如果需要自定义登录、注册流程,可在Blazor组件中注入SignInManager<ApplicationUser>,调用其PasswordSignInAsync等方法实现自定义登录逻辑;注册则调用UserManager.CreateAsync方法,同时传入自定义字段的值即可。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.26 05:05:00