直到ASP.NET Core 1.0 RC1:
它是System.Security.Claims命名空间中的User.GetUserId().
自ASP.NET Core 1.0 RC2:
您现在必须使用UserManager.您可以创建一个方法来获取当前用户:
private Task<ApplicationUser> GetCurrentUserAsync() => _userManager.GetUserAsync(HttpContext.User);
并获取对象的用户信息:
var user = await GetCurrentUserAsync();
var userId = user?.Id;
string mail = user?.Email;
ASP.NET Core 2.1和2.2中的更新:
在控制器中:
public class YourControllerNameController : Controller
{
public 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
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);
}
}
然后你应该IHttpContextAccessor
在Startup
课堂上注册如下:
public void ConfigureServices(IServiceCollection services)
{
services.TryAddSingleton<IHttpContextAccessor, HttpContextAccessor>();
// Or you can also register as follows
services.AddHttpContextAccessor();
}