如何在ASP.NET Identity Web Forms中获取未暴露的UserManager对象
在Web Forms Identity中获取UserManager对象并查询非当前用户用户名
要解决UserManager未对外暴露的问题,你可以通过以下方式获取实例并完成用户名查询:
方法一:通过静态工具类统一获取UserManager
在项目的IdentityConfig.cs(或自定义的Identity初始化文件)中添加静态工具类,统一提供配置好的UserManager实例:
public static class IdentityHelper { public static UserManager<ApplicationUser> GetUserManager() { var userStore = new UserStore<ApplicationUser>(new ApplicationDbContext()); var userManager = new UserManager<ApplicationUser>(userStore); // 可在此添加全局配置的验证规则、令牌提供器等 return userManager; } }
之后在需要查询的地方直接调用:
var userManager = IdentityHelper.GetUserManager(); string userName = userManager.FindById(userID).UserName;
方法二:在使用页面直接实例化
如果仅在局部页面使用,可直接在页面代码中创建UserManager实例(注意数据库上下文的释放):
using (var dbContext = new ApplicationDbContext()) { var userStore = new UserStore<ApplicationUser>(dbContext); var userManager = new UserManager<ApplicationUser>(userStore); string userName = userManager.FindById(userID).UserName; }
注意:如果项目中已有全局配置的Identity服务,确保UserManager的配置(如密码规则、验证逻辑)与全局保持一致,避免行为不一致。
内容的提问来源于stack exchange,提问作者Joshua Ginn
相关产品推荐
相关产品推荐

