简体   繁体   中英

User.Identity.GetUserId() always returns null in .net Core

I am using Microsoft Identity. But in my code the Identity method User.Identity.GetUserId always return null.

Here is my code.

private string GetUserId()
    {
        string userId = "";

        try
        {
            if (_identity != null)
                userId = _identity.GetUserId();
            else
                userId = User.Identity.GetUserId();
        }
        catch (Exception ex)
        {
            _logger.Error(ex.Message, ex);
            throw;
        }

        return userId;
    }

User.Identity.GetUserId() no longer exists, but the id is available as a claim on your principal.

The first and easiest is just pull out the claim:

userId = User.FindFirstValue(ClaimTypes.NameIdentifier);

If you have an instance of UserManager<TUser> , then you can use the GetUserId() method on that using DI:

userId = _userManager.GetUserId(User);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM