251

我以前用 MVC5 做过这个,User.Identity.GetUserId()但这似乎在这里不起作用。User.Identity没有GetUserId()方法。

我正在使用Microsoft.AspNet.Identity.

4

19 回答 19

246

在 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;
     }
}
于 2018-09-02T08:08:04.177 回答
115

直到 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;

注意: 您可以不使用像这样编写单行的方法来做到这一点string mail = (await _userManager.GetUserAsync(HttpContext.User))?.Email,但它不尊重单一责任原则。最好隔离获取用户的方式,因为如果有一天您决定更改用户管理系统,例如使用身份以外的其他解决方案,那将变得很痛苦,因为您必须审查整个代码。

于 2016-02-01T10:31:48.453 回答
104

你可以在你的控制器中得到它:

using System.Security.Claims;
var userId = this.User.FindFirstValue(ClaimTypes.NameIdentifier);

或者像.Core v1.0之前一样写一个扩展方法

using System;
using System.Security.Claims;

namespace Shared.Web.MvcExtensions
{
    public static class ClaimsPrincipalExtensions
    {
        public static string GetUserId(this ClaimsPrincipal principal)
        {
            if (principal == null)
                throw new ArgumentNullException(nameof(principal));

            return principal.FindFirst(ClaimTypes.NameIdentifier)?.Value;
        }
    }
}

并获取用户 ClaimsPrincipal 可用的任何地方

using Microsoft.AspNetCore.Mvc;
using Shared.Web.MvcExtensions;

namespace Web.Site.Controllers
{
    public class HomeController : Controller
    {
        public IActionResult Index()
        {
            return Content(this.User.GetUserId());
        }
    }
}
于 2016-08-09T09:50:54.217 回答
39

我包括使用 System.Security.Claims 并且可以访问 GetUserId() 扩展方法

注意:我已经使用了 Microsoft.AspNet.Identity 但无法获得扩展方法。所以我想它们都必须相互结合使用

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

编辑:这个答案现在已经过时了。查看 Soren 或 Adrien 的答案,了解在 CORE 1.0 中实现这一目标的过时方法

于 2015-06-08T05:32:12.517 回答
28

仅适用于 .NET Core 2.0 在类中获取登录用户的 UserID 需要以下内容Controller

var userId = this.User.FindFirstValue(ClaimTypes.NameIdentifier);

或者

var userId = HttpContext.User.FindFirstValue(ClaimTypes.NameIdentifier);

例如

contact.OwnerID = this.User.FindFirstValue(ClaimTypes.NameIdentifier);
于 2018-02-14T21:45:51.167 回答
20

如本文某处所述,GetUserId() 方法已移至 UserManager。

private readonly UserManager<ApplicationUser> _userManager;

public YourController(UserManager<ApplicationUser> userManager)
{
    _userManager = userManager;
}

public IActionResult MyAction()
{
    var userId = _userManager.GetUserId(HttpContext.User);

    var model = GetSomeModelByUserId(userId);

    return View(model);
}

如果您启动了一个空项目,您可能需要在 startup.cs 中将 UserManger 添加到您的服务中。否则应该已经是这种情况了。

于 2016-10-22T07:41:02.143 回答
14

你必须导入 Microsoft.AspNetCore.Identity & System.Security.Claims

// to get current user ID
var userId = User.FindFirstValue(ClaimTypes.NameIdentifier);

// to get current user info
var user = await _userManager.FindByIdAsync(userId);
于 2017-11-16T03:26:21.527 回答
9

在 .net core 3.1(和其他更新的版本)中,您可以使用:

private readonly UserManager<IdentityUser> _userManager;

public ExampleController(UserManager<IdentityUser> userManager)
{
    _userManager = userManager;
}

然后:

string userId = _userManager.GetUserId(User);

或异步:

var user = await _userManager.GetUserAsync(User);
var userId = user.Id;

在这一点上,我试图弄清楚为什么你会使用一个而不是另一个。我知道异步的一般好处,但看到这两个经常使用。如果有人知道,请发表一些评论。

于 2020-09-21T01:02:15.220 回答
8

对于 ASP.NET Core 2.0、Entity Framework Core 2.0、AspNetCore.Identity 2.0 api ( https://github.com/kkagill/ContosoUniversity-Backend ):

Id更改为User.Identity.Name

    [Authorize, HttpGet("Profile")]
    public async Task<IActionResult> GetProfile()
    {
        var user = await _userManager.FindByIdAsync(User.Identity.Name);

        return Json(new
        {
            IsAuthenticated = User.Identity.IsAuthenticated,
            Id = User.Identity.Name,
            Name = $"{user.FirstName} {user.LastName}",
            Type = User.Identity.AuthenticationType,
        });
    }

回复:

在此处输入图像描述

于 2018-03-08T10:00:28.830 回答
7

对于ASP.NET 5.0,我有一个扩展方法如下:

using System;
using System.ComponentModel;
using System.Security.Claims;

namespace YOUR_PROJECT.Presentation.WebUI.Extensions
{
    public static class ClaimsPrincipalExtensions
    {
        public static TId GetId<TId>(this ClaimsPrincipal principal)
        {
            if (principal == null || principal.Identity == null || 
                !principal.Identity.IsAuthenticated)
            {
                throw new ArgumentNullException(nameof(principal));
            }

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

            if (typeof(TId) == typeof(string) || 
                typeof(TId) == typeof(int) || 
                typeof(TId) == typeof(long) || 
                typeof(TId) == typeof(Guid))
            {
                var converter = TypeDescriptor.GetConverter(typeof(TId));

                return (TId)converter.ConvertFromInvariantString(loggedInUserId);
            }

            throw new InvalidOperationException("The user id type is invalid.");
        }

        public static Guid GetId(this ClaimsPrincipal principal)
        {
            return principal.GetId<Guid>();
        }
    }
}

所以你可以像这样使用它:

using Microsoft.AspNetCore.Mvc;
using YOUR_PROJECT.Presentation.WebUI.Extensions;

namespace YOUR_PROJECT.Presentation.WebUI.Controllers
{
    public class YourController :Controller
    {
        public IActionResult YourMethod()
        {
            // If it's Guid
            var userId = User.GetId();

            // Or
            // var userId = User.GetId<int>();

            return View();
        }
    }
}
于 2021-01-18T17:45:18.327 回答
6

在里面APiController

User.FindFirst(ClaimTypes.NameIdentifier).Value

这样的事情你会得到索赔

于 2018-09-03T11:06:09.893 回答
5

尽管 Adrien 的答案是正确的,但您可以在一行中完成所有操作。不需要额外的功能或混乱。

它工作我在 ASP.NET Core 1.0 中检查过

var user = await _userManager.GetUserAsync(HttpContext.User);

然后您可以获得变量的其他属性,例如user.Email. 我希望这可以帮助别人。

于 2017-02-27T18:29:31.323 回答
3

为了在 razor 视图中获取当前用户 ID,我们可以像这样在视图中注入 UserManager:

@inject Microsoft.AspNetCore.Identity.UserManager<ApplicationUser> _userManager
@{ string userId = _userManager.GetUserId(User); }

希望对你有帮助。

于 2020-06-02T07:44:34.700 回答
1

User.Identity.GetUserId();

在 asp.net 身份核心 2.0 中不存在。在这方面,我以不同的方式进行了管理。由于获取用户信息,我创建了一个用于整个应用程序的通用类。

创建公共类 PCommon & 接口 IPCommon 添加参考using System.Security.Claims

using Microsoft.AspNetCore.Http;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Claims;
using System.Threading.Tasks;

namespace Common.Web.Helper
{
    public class PCommon: IPCommon
    {
        private readonly IHttpContextAccessor _context;
        public PayraCommon(IHttpContextAccessor context)
        {
            _context = context;
        }
        public int GetUserId()
        {
            return Convert.ToInt16(_context.HttpContext.User.FindFirstValue(ClaimTypes.NameIdentifier));
        }
        public string GetUserName()
        {
            return _context.HttpContext.User.Identity.Name;
        }

    }
    public interface IPCommon
    {
        int GetUserId();
        string GetUserName();        
    }    
}

这里是普通类的实现

using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Rendering;
using Microsoft.Extensions.Logging;
using Pay.DataManager.Concreate;
using Pay.DataManager.Helper;
using Pay.DataManager.Models;
using Pay.Web.Helper;
using Pay.Web.Models.GeneralViewModels;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace Pay.Controllers
{

    [Authorize]
    public class BankController : Controller
    {

        private readonly IUnitOfWork _unitOfWork;
        private readonly ILogger _logger;
        private readonly IPCommon _iPCommon;


        public BankController(IUnitOfWork unitOfWork, IPCommon IPCommon, ILogger logger = null)
        {
            _unitOfWork = unitOfWork;
            _iPCommon = IPCommon;
            if (logger != null) { _logger = logger; }
        }


        public ActionResult Create()
        {
            BankViewModel _bank = new BankViewModel();
            CountryLoad(_bank);
            return View();
        }

        [HttpPost, ActionName("Create")]
        [ValidateAntiForgeryToken]
        public async Task<IActionResult> Insert(BankViewModel bankVM)
        {

            if (!ModelState.IsValid)
            {
                CountryLoad(bankVM);
                //TempData["show-message"] = Notification.Show(CommonMessage.RequiredFieldError("bank"), "Warning", type: ToastType.Warning);
                return View(bankVM);
            }


            try
            {
                bankVM.EntryBy = _iPCommon.GetUserId();
                var userName = _iPCommon.GetUserName()();
                //_unitOfWork.BankRepo.Add(ModelAdapter.ModelMap(new Bank(), bankVM));
                //_unitOfWork.Save();
               // TempData["show-message"] = Notification.Show(CommonMessage.SaveMessage(), "Success", type: ToastType.Success);
            }
            catch (Exception ex)
            {
               // TempData["show-message"] = Notification.Show(CommonMessage.SaveErrorMessage("bank"), "Error", type: ToastType.Error);
            }
            return RedirectToAction(nameof(Index));
        }



    }
}

在插入操作中获取用户 ID 和名称

_iPCommon.GetUserId();

谢谢,马克苏德

于 2018-08-05T11:15:07.130 回答
0

使用可以使用

string userid = User.FindFirst("id").Value;

由于某种原因,NameIdentifier 现在检索用户名(.net core 2.2)

于 2019-01-22T21:03:48.070 回答
0

确保您已启用 Windows 身份验证。如果您启用了匿名身份验证,您可能会得到一个空字符串。

https://docs.microsoft.com/en-us/aspnet/core/security/authentication/windowsauth?view=aspnetcore-3.1&tabs=visual-studio

于 2021-01-15T21:01:37.197 回答
0

如果您使用的是 JWT 令牌,则此代码有效:

User.FindFirstValue("sub");
于 2022-01-24T22:05:52.883 回答
-1

作为处理其他人配置文件的管理员并且您需要获取您正在处理的配置文件的 Id,您可以使用 ViewBag 来捕获 Id 例如 ViewBag.UserId = userId; 而 userId 是您正在处理的方法的字符串参数。

    [HttpGet]

    public async Task<IActionResult> ManageUserRoles(string userId)
    {

          ViewBag.UserId = userId;


        var user = await userManager.FindByIdAsync(userId);

        if (user == null)
        {
            ViewBag.ErrorMessage = $"User with Id = {userId} cannot be found";
            return View("NotFound");
        }

        var model = new List<UserRolesViewModel>();

        foreach (var role in roleManager.Roles)
        {
            var userRolesViewModel = new UserRolesViewModel
            {
                RoleId = role.Id,
                RoleName = role.Name
            };

            if (await userManager.IsInRoleAsync(user, role.Name))
            {
                userRolesViewModel.IsSelected = true;
            }
            else
            {
                userRolesViewModel.IsSelected = false;
            }

            model.Add(userRolesViewModel);
        }
        return View(model);
    }
于 2020-03-03T17:35:14.767 回答
-12

如果您想在 ASP.NET MVC 控制器中使用它,请使用

using Microsoft.AspNet.Identity;

User.Identity.GetUserId();

您需要添加using语句,因为GetUserId()没有它就不会存在。

于 2015-06-08T05:46:20.080 回答