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());
}
}
}
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);
[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,
});
}
// 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();
12 回答
直到ASP.NET Core 1.0 RC1 :
它是System.Security.Claims命名空间中的User.GetUserId() .
自ASP.NET Core 1.0 RC2 :
您现在必须使用UserManager . 您可以创建一个方法来获取当前用户:
并获取对象的用户信息:
Note : 你可以不使用像_632003这样编写单行的方法来做到这一点,但是它并没有更好地隔离你获得用户的方式,因为如果有一天你决定改变你的用户管理系统,比如使用另一个解决方案而不是身份,它因为你必须检查整个代码,所以会很痛苦 .
you can get it in your controller:
or write an extension method like before .Core v1.0
并获得用户ClaimsPrincipal可用的任何地方:
我包括使用System.Security.Claims,我可以访问GetUserId()扩展方法
注意:我已经使用了Microsoft.AspNet.Identity,但无法获得扩展方法 . 所以我猜两者都必须相互结合使用
EDIT :这个答案现在已经过时了 . 看看Soren 's or Adrien'的答案,找到了在CORE 1.0中实现这一目标的过时方法
仅适用于.NET Core 2.0以下是获取
Controller
类中已登录用户的UserID所必需的:要么
例如
正如本文中的某处所述,GetUserId()方法已移至UserManager .
如果您启动了一个空项目,则可能需要在startup.cs中将UserManger添加到您的服务中 . 否则这应该是这种情况 .
ASP.NET Core 2.1和2.2中的
更新:
In the Controller:
In some other class:
然后你应该在
Startup
类中注册IHttpContextAccessor
,如下所示:虽然Adrien的答案是正确的,但你可以单行完成 . 不需要额外的功能或混乱 .
它工作我在ASP.NET Core 1.0中检查它
然后你可以获得变量的其他属性,如
user.Email
. 我希望这可以帮助别人 .对于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
响应:
你必须导入Microsoft.AspNetCore.Identity和System.Security.Claims
在
APiController
像这样的东西,你会得到索赔
User.Identity.GetUserId();
asp.net identity core 2.0中不存在 . 在这方面,我以不同的方式管理 . 我已经创建了一个用于整个应用程序的公共类,因为它获取了用户信息 .
create a common class PCommon & interface IPCommon 正在添加参考
using System.Security.Claims
这里执行常见的类
在插入操作中获取userId和name
谢谢,马克苏德
如果您想在ASP.NET MVC Controller中使用它,请使用
你需要添加
using
语句,因为如果没有它,GetUserId()
将不存在 .