【问题标题】:Asp.Net Core Identity Get Integer User IdAsp.Net Core Identity 获取整数用户 ID
【发布时间】:2023-03-16 11:28:01
【问题描述】:

我有一个 ASP.NET MVC Core n 层应用程序。我将默认主键更改为整数。没有问题。但我尝试 GetUserId() UserManager 的默认方法返回字符串。是我自己写的方法还是我做错了什么?

//In controller
public int GetLoggedUserId()
{
    //it's return still string and of course i can't compile my code 
    //problem is here
    return UserService.GetUserId(); 
}

public class ApplicationUser : IdentityUser<int>
{
    [MaxLength(255)]
    public string LogoPath { get; set; }
}

public partial class MyUserManager : UserManager<ApplicationUser>
{
    private readonly IUnitOfWork _unitOfWork;

    public MyUserManager(IUnitOfWork unitOfWork,
                            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)
    {
        _unitOfWork = unitOfWork;
    }
}

services.AddDefaultIdentity<ApplicationUser>()
        .AddEntityFrameworkStores<MyDbContext>()
        .AddUserManager<MyUserManager>()
        .AddDefaultTokenProviders();

【问题讨论】:

    标签: c# asp.net-mvc asp.net-core dependency-injection asp.net-identity


    【解决方案1】:

    默认方法.GetUserId() 确实返回一个字符串。这个问题可以通过编写一个自定义方法来解决,该方法从数据库中访问 int 值并将其返回给您的GetLoggedUserId() 方法。

    【讨论】:

      【解决方案2】:

      用户 ID 存储为对用户主体的声明。您可以通过(在控制器/页面/视图中)访问它:

      string userId = User.FindFirstValue(ClaimTypes.NameIdentifier);
      

      声明存储为字符串,所以如果你需要一个 int:

      var userIdClaim = User.FindFirstValue(ClaimTypes.NameIdentifier);
      var userId = int.TryParse(userIdClaim, out var id) ? id : 0;
      

      用户主体存在于HttpContext,因此在User 便利属性存在的地方之外,您需要注入IHttpContextAccessor,然后:

      var userIdClaim = _httpContextAccessor.HttpContext?.User.FindFirstValue(ClaimTypes.NameIdentifier);
      

      【讨论】:

        猜你喜欢
        • 2016-12-09
        • 2021-07-09
        • 2017-05-12
        • 2014-05-02
        • 2018-01-08
        • 1970-01-01
        • 2021-05-16
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多