Asp.Net核心身份获取整数用户ID

时间:2019-06-27 14:44:53

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

我有一个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();

2 个答案:

答案 0 :(得分:1)

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

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

该声明存储为字符串,因此,如果您需要一个整数:

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);

答案 1 :(得分:0)

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