Asp.net

如何在 ASP.NET Core 中獲取目前登錄的使用者 ID?

  • June 8, 2015

我以前用 MVC5 做過這個,User.Identity.GetUserId()但這似乎在這裡不起作用。User.Identity沒有GetUserId()方法。

我正在使用Microsoft.AspNet.Identity.

我包括使用 System.Security.Claims 並且可以訪問 GetUserId() 擴展方法

注意:我已經使用了 Microsoft.AspNet.Identity 但無法獲得擴展方法。所以我想它們都必須相互結合使用

using Microsoft.AspNet.Identity;
using System.Security.Claims;

編輯:這個答案現在已經過時了。查看 Soren 或 Adrien 的答案,了解在 CORE 1.0 中實現這一目標的過時方法

在 ASP.NET Core 版本中更新 >= 2.0

在控制器中:

public class YourControllerNameController : Controller
{
   private readonly UserManager<ApplicationUser> _userManager;
   
   public YourControllerNameController(UserManager<ApplicationUser> userManager)
   {
       _userManager = userManager;
   }

   public async Task<IActionResult> YourMethodName()
   {
       var userId =  User.FindFirstValue(ClaimTypes.NameIdentifier) // will give the user's userId
       var userName =  User.FindFirstValue(ClaimTypes.Name) // will give the user's userName
       
       // For ASP.NET Core <= 3.1
       ApplicationUser applicationUser = await _userManager.GetUserAsync(User);
       string userEmail = applicationUser?.Email; // will give the user's Email

      // For ASP.NET Core >= 5.0
      var userEmail =  User.FindFirstValue(ClaimTypes.Email) // will give the user's Email
   }
}

在其他一些類中:

public class OtherClass
{
   private readonly IHttpContextAccessor _httpContextAccessor;
   public OtherClass(IHttpContextAccessor httpContextAccessor)
   {
      _httpContextAccessor = httpContextAccessor;
   }

  public void YourMethodName()
  {
     var userId = _httpContextAccessor.HttpContext.User.FindFirstValue(ClaimTypes.NameIdentifier);
  }
}

然後你應該IHttpContextAccessorStartup類中註冊如下:

public void ConfigureServices(IServiceCollection services)
{
   services.TryAddSingleton<IHttpContextAccessor, HttpContextAccessor>();

   // Or you can also register as follows

   services.AddHttpContextAccessor();
}

為了提高可讀性,編寫擴展方法如下:

public static class ClaimsPrincipalExtensions
{
   public static T GetLoggedInUserId<T>(this ClaimsPrincipal principal)
   {
       if (principal == null)
           throw new ArgumentNullException(nameof(principal));

       var loggedInUserId = principal.FindFirstValue(ClaimTypes.NameIdentifier);

       if (typeof(T) == typeof(string))
       {
           return (T)Convert.ChangeType(loggedInUserId, typeof(T));
       }
       else if (typeof(T) == typeof(int) || typeof(T) == typeof(long))
       {
           return loggedInUserId != null ? (T)Convert.ChangeType(loggedInUserId, typeof(T)) : (T)Convert.ChangeType(0, typeof(T));
       }
       else
       {
           throw new Exception("Invalid type provided");
       }
   }

   public static string GetLoggedInUserName(this ClaimsPrincipal principal)
   {
       if (principal == null)
           throw new ArgumentNullException(nameof(principal));

       return principal.FindFirstValue(ClaimTypes.Name);
   }

   public static string GetLoggedInUserEmail(this ClaimsPrincipal principal)
   {
       if (principal == null)
           throw new ArgumentNullException(nameof(principal));

       return principal.FindFirstValue(ClaimTypes.Email);
   }
}

然後使用如下:

public class YourControllerNameController : Controller
{
   public IActionResult YourMethodName()
   {
       var userId = User.GetLoggedInUserId<string>(); // Specify the type of your UserId;
       var userName = User.GetLoggedInUserName();
       var userEmail = User.GetLoggedInUserEmail();
   }
}

public class OtherClass
{
    private readonly IHttpContextAccessor _httpContextAccessor;
    public OtherClass(IHttpContextAccessor httpContextAccessor)
    {
        _httpContextAccessor = httpContextAccessor;
    }

    public void YourMethodName()
    {
        var userId = _httpContextAccessor.HttpContext.User.GetLoggedInUserId<string>(); // Specify the type of your UserId;
    }
}

引用自:https://stackoverflow.com/questions/30701006