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

问题描述 投票:104回答:13

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

我正在使用Microsoft.AspNet.Identity

asp.net asp.net-identity asp.net-core-mvc asp.net-core-1.0
13个回答
97
投票

直到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这样的单行编写方法的情况下执行此操作,但它不遵守单一责任原则。最好隔离你获得用户的方式,因为如果有一天你决定改变你的用户管理系统,比如使用另一个解决方案而不是身份,那么由于你必须检查你的整个代码,它会变得很痛苦。


2
投票

APiController

User.FindFirst(ClaimTypes.NameIdentifier).Value

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


1
投票

User.Identity.GetUserId();

asp.net identity core 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));
        }



    }
}

在插入操作中获取userId和name

_iPCommon.GetUserId();

谢谢,我的意思是


0
投票

使用可以使用

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

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


-9
投票

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

using Microsoft.AspNet.Identity;

User.Identity.GetUserId();

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


74
投票

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

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());
        }
    }
}

71
投票

ASP.NET Core 2.1和2.2中的更新:

在控制器中:

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
    }
}

在其他一些课程中:

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);
   }
}

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

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

    // Or you can also register as follows

    services.AddHttpContextAccessor();
}

36
投票

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

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

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

编辑:这个答案现在已经过时了。看看Soren's或Adrien的回答,找出在CORE 1.0中实现这一目标的过时方式


23
投票

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

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

要么

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

EG

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

14
投票

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


5
投票

虽然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


4
投票

你必须导入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);
© www.soinside.com 2019 - 2024. All rights reserved.