创建另一个模型Testimonial
时,我将活动用户的Id
存储为Author
,其字符串类似于:00b9c6aa-010c-4cbd-ac16-c72d05e7906a
。在另一个视图中,我想为每个Id
显示与Testimonial
相关联的名称和其他用户信息。该视图将包含来自许多不同用户的信息,而不仅仅是主动记录的用户。我无法弄清楚如何通过Id
向用户提供他们的信息。
如何通过IdentityUser
获取Id
?
包含用户的所有表都是默认加上一些其他列。在名为AspNetUsers
的表格中,我有Id
,FirstName
,Email
等。Id
是关键值,我想知道如何(在Testimonial
的控制器内)检索给定Id
的信息。
答案 0 :(得分:3)
IdentityConfig.cs //配置此应用程序中使用的应用程序用户管理器。 UserManager在ASP.NET Identity中定义,并由应用程序使用。
public class ApplicationUserManager : UserManager<ApplicationUser>
{
public ApplicationUserManager(IUserStore<ApplicationUser> store)
: base(store)
{
}
public static ApplicationUserManager Create(IdentityFactoryOptions<ApplicationUserManager> options, IOwinContext context)
{
var manager = new ApplicationUserManager(new UserStore<ApplicationUser>(context.Get<ApplicationDbContext>()));
// Configure validation logic for usernames
manager.UserValidator = new UserValidator<ApplicationUser>(manager)
{
AllowOnlyAlphanumericUserNames = false,
RequireUniqueEmail = true
};
// Configure validation logic for passwords
manager.PasswordValidator = new PasswordValidator
{
RequiredLength = 6,
RequireNonLetterOrDigit = false,
RequireDigit = false,
RequireLowercase = false,
RequireUppercase = false,
};
manager.EmailService = new EmailService();
var dataProtectionProvider = options.DataProtectionProvider;
if (dataProtectionProvider != null)
{
manager.UserTokenProvider = new DataProtectorTokenProvider<ApplicationUser>(dataProtectionProvider.Create("ASP.NET Identity"));
}
return manager;
}
}
public class ApplicationSignInManager : SignInManager<ApplicationUser, string>
{
public ApplicationSignInManager(ApplicationUserManager userManager, IAuthenticationManager authenticationManager) :
base(userManager, authenticationManager) { }
public override Task<ClaimsIdentity> CreateUserIdentityAsync(ApplicationUser user)
{
return user.GenerateUserIdentityAsync((ApplicationUserManager)UserManager);
}
public static ApplicationSignInManager Create(IdentityFactoryOptions<ApplicationSignInManager> options, IOwinContext context)
{
return new ApplicationSignInManager(context.GetUserManager<ApplicationUserManager>(), context.Authentication);
}
}
在您的控制器中定义以下属性
private ApplicationUserManager _userManager;
public ApplicationUserManager UserManager
{
get
{
return _userManager ?? HttpContext.GetOwinContext().GetUserManager<ApplicationUserManager>();
}
private set
{
_userManager = value;
}
}
private ApplicationSignInManager _signInManager;
public ApplicationSignInManager SignInManager
{
get
{
return _signInManager ?? HttpContext.GetOwinContext().Get<ApplicationSignInManager>();
}
private set { _signInManager = value; }
}
您可以在控制器中使用以下方法
var user = await UserManager.FindByIdAsync("00b9c6aa-010c-4cbd-ac16-c72d05e7906a");
您可以像以下
一样获取登录用户var user = await UserManager.FindByIdAsync(await SignInManager.GetVerifiedUserIdAsync());