首页 文章

如何在ASP.NET Core中获取当前登录的用户ID

提问于
浏览
86

我之前用MVC5使用 User.Identity.GetUserId() 完成了这个,但这似乎不适用于此 . User.Identity 没有 GetUserId() 方法

我正在使用 Microsoft.AspNet.Identity

12 回答

  • -6

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

    Note : 你可以不使用像_632003这样编写单行的方法来做到这一点,但是它并没有更好地隔离你获得用户的方式,因为如果有一天你决定改变你的用户管理系统,比如使用另一个解决方案而不是身份,它因为你必须检查整个代码,所以会很痛苦 .

  • 1

    you can get it in your controller:

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

    or write an extension method like before .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());
            }
        }
    }
    
  • 2

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

    注意:我已经使用了Microsoft.AspNet.Identity,但无法获得扩展方法 . 所以我猜两者都必须相互结合使用

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

    EDIT :这个答案现在已经过时了 . 看看Soren 's or Adrien'的答案,找到了在CORE 1.0中实现这一目标的过时方法

  • 5

    仅适用于.NET Core 2.0以下是获取 Controller 类中已登录用户的UserID所必需的:

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

    要么

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

    例如

    contact.OwnerID = this.User.FindFirstValue(ClaimTypes.NameIdentifier);
    
  • 85

    正如本文中的某处所述,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添加到您的服务中 . 否则这应该是这种情况 .

  • 19

    ASP.NET Core 2.1和2.2中的

    更新:

    In the Controller:

    public class YourControllerNameController : Controller
    {
        public IActionResult YourMethodName()
        {
            var userId =  User.FindFirst(ClaimTypes.NameIdentifier).Value // will give the user's userId
            var userName =  User.FindFirst(ClaimTypes.Name).Value // will give the user's userName
            var userEmail =  User.FindFirst(ClaimTypes.Email).Value // will give the user's Email
        }
    }
    

    In some other class:

    public class OtherClass
    {
        private readonly IHttpContextAccessor _httpContextAccessor;
        public OtherClass(IHttpContextAccessor httpContextAccessor)
        {
           _httpContextAccessor = httpContextAccessor;
        }
    
       public void YourMethodName()
       {
          var userId = _httpContextAccessor.HttpContext.User.FindFirst(ClaimTypes.NameIdentifier).Value;
          // or
          var userId = _httpContextAccessor.HttpContext.User.FindFirstValue(ClaimTypes.NameIdentifier);
       }
    }
    

    然后你应该在 Startup 类中注册 IHttpContextAccessor ,如下所示:

    public void ConfigureServices(IServiceCollection services)
    {
        services.TryAddSingleton<IHttpContextAccessor, HttpContextAccessor>();
    
        // Or you can also register as follows
    
        services.AddHttpContextAccessor();
    }
    
  • 54

    虽然Adrien的答案是正确的,但你可以单行完成 . 不需要额外的功能或混乱 .

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

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

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

  • 5

    对于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,
            });
        }
    

    响应:

    enter image description here

  • 31

    你必须导入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);
    
  • 12

    APiController

    User.FindFirst(ClaimTypes.NameIdentifier).Value
    

    像这样的东西,你会得到索赔

  • 11

    User.Identity.GetUserId();

    asp.net identity core 2.0中不存在 . 在这方面,我以不同的方式管理 . 我已经创建了一个用于整个应用程序的公共类,因为它获取了用户信息 .

    create a common class PCommon & interface 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));
            }
    
    
    
        }
    }
    

    在插入操作中获取userId和name

    _iPCommon.GetUserId();
    

    谢谢,马克苏德

  • 3

    如果您想在ASP.NET MVC Controller中使用它,请使用

    using Microsoft.AspNet.Identity;
    
    User.Identity.GetUserId();
    

    你需要添加 using 语句,因为如果没有它, GetUserId() 将不存在 .

相关问题