gpt4 book ai didi

c# - 扩展用户管理器

转载 作者:太空狗 更新时间:2023-10-29 20:02:27 26 4
gpt4 key购买 nike

在我的 .NET Core 2.0 MVC 项目中,我添加了额外的值来扩展 ApplicationUser

public class ApplicationUser : IdentityUser
{
public string Name { get; set; }
public DateTime DateCreated { get; set; }
public DateTime DateUpdated { get; set; }
public DateTime LastLogin{ get; set; }

}

在 _LoginPartial 中,我想获取名称,而不是默认获取的用户名

@using Microsoft.AspNetCore.Identity
@using RioTintoQRManager.Models

@inject SignInManager<ApplicationUser> SignInManager
@inject UserManager<ApplicationUser> UserManager
@if (SignInManager.IsSignedIn(User))
{
@UserManager.GetUserName(User)
}

我如何扩展 UserManager,或创建一个像 UserManager.GetUserName 一样在 View 中可用的新方法?

最佳答案

您的 View 不需要自己调用后端服务,您应该通过 @Model 向它提供所需的所有信息。或通过 ViewBag/ViewData/Session .
但是,如果您需要获取当前用户,您可以使用:

var user = await UserManager.GetUserAsync(User);
string userName = user.Name;

如果你想拥有自己的UserManager ,不过,您必须这样做:

public class MyManager : UserManager<ApplicationUser>
{
public MyManager(IUserStore<ApplicationUser> store, IOptions<IdentityOptions> optionsAccessor, IPasswordHasher<ApplicationUser> passwordHasher, IEnumerable<IUserValidator<ApplicationUser>> userValidators, IEnumerable<IPasswordValidator<ApplicationUser>> passwordValidators, ILookupNormalizer keyNormalizer, IdentityErrorDescriber errors, IServiceProvider services, ILogger<UserManager<ApplicationUser>> logger) : base(store, optionsAccessor, passwordHasher, userValidators, passwordValidators, keyNormalizer, errors, services, logger)
{

}

public async Task<string> GetNameAsync(ClaimsPrincipal principal)
{
var user = await GetUserAsync(principal);
return user.Name;
}
}

并将其添加到服务中:

services.AddIdentity<ApplicationUser, ApplicationRole>()
.AddEntityFrameworkStores<SomeContext>()
.AddUserManager<MyManager>()
.AddDefaultTokenProviders();

然后您需要替换对 UserManager<ApplicationUser> 的引用对于 MyManager .

关于c# - 扩展用户管理器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48673222/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com