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

时间:2015-06-08 03:53:30

标签: asp.net asp.net-identity asp.net-core-mvc asp.net-core-1.0

我之前使用User.Identity.GetUserId()使用MVC5完成了此操作,但这似乎无法在此处运行。 User.Identity没有GetUserId()方法

我正在使用Microsoft.AspNet.Identity

18 个答案:

答案 0 :(得分:92)

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

答案 1 :(得分:68)

你可以在控制器中获取它:

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

答案 2 :(得分:57)

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

答案 3 :(得分:35)

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

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

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

修改: 这个答案现在已经过时了。请看Soren或Adrien的答案,了解在CORE 1.0中实现这一目标的过时方式

答案 4 :(得分:21)

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

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

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

e.g。

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

答案 5 :(得分: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添加到您的服务中。否则这应该是这种情况。

答案 6 :(得分:5)

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

答案 7 :(得分:5)

虽然阿德里安的答案是正确的,但你可以单行完成。不需要额外的功能或混乱。

它可以在ASP.NET Core 1.0中检查它

$json = json_decode($string, true);
$contacts = $json['return']['contacts'];

foreach($contacts as $contact){
  echo $contact['contact']['id'];
}

然后你可以获得变量的其他属性,如var user = await _userManager.GetUserAsync(HttpContext.User); 。我希望这有助于某人。

答案 8 :(得分: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

答案 9 :(得分:4)

你必须导入Microsoft.AspNetCore.Identity&amp; 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);

答案 10 :(得分:3)

在.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;

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

答案 11 :(得分:2)

APiController

User.FindFirst(ClaimTypes.NameIdentifier).Value

这样的事情你会得到索赔的

答案 12 :(得分: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();

谢谢, 马克苏德

答案 13 :(得分:1)

要在剃刀视图中获取当前的用户ID,我们可以在如下视图中注入UserManager:

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

我希望您觉得它有用。

答案 14 :(得分:0)

使用可以使用

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

出于某种原因,NameIdentifier现在可以检索用户名(.net核心2.2)

答案 15 :(得分:0)

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

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

答案 16 :(得分:-1)

作为在其他人的个人资料上工作的管理员,您需要获取正在使用的个人资料的ID,因此可以使用ViewBag捕获ID,例如,ViewBag.UserId = userId;而userId是您正在使用的方法的字符串参数。

to make-people
create-people 4 [setup-turtles] 
end

to setup-turtles  ;;Turtle Procedure
set shape "person"
let y-coordinates (list -8 -7 -6 -5)
let remove-index random length y-coordinates
set ycor item remove-index y-coordinates
set y-coordinates remove-item remove-index y-coordinates
set xcor 19 



end


答案 17 :(得分:-7)

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

using Microsoft.AspNet.Identity;

User.Identity.GetUserId();

您需要添加using声明,因为GetUserId()在没有它的情况下不会出现。