12 ответов:
вы можете получить его в вашем контроллере:
var userId = this.User.FindFirstValue(ClaimTypes.NameIdentifier);или написать метод расширения, как и раньше .Основной В1.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()); } } }
Я включил использование системы.Безопасность.Претензии и я мог бы получить доступ к методу расширения GetUserId ()
NB: у меня было использование Microsoft.сеть САШ.Identity уже, но не смог получить метод расширения. Поэтому я думаю, что оба они должны использоваться в сочетании друг с другом
using Microsoft.AspNet.Identity; using System.Security.Claims;EDIT: Этот ответ устарел. Посмотрите на ответ Сорена или Адриена для датированного способа достижения этого в CORE 1.0
для .NET Core 2.0 требуется только следующее, Чтобы получить идентификатор пользователя вошедшего в систему пользователя в
Controllerкласс:var userId = this.User.FindFirstValue(ClaimTypes.NameIdentifier);или
var userId = HttpContext.User.FindFirstValue(ClaimTypes.NameIdentifier);например
contact.OwnerID = this.User.FindFirstValue(ClaimTypes.NameIdentifier);
как указано где-то в этом посте, метод 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); }Если вы запустили пустой проект, вам может потребоваться добавить UserManger в свои службы при запуске.цезий. В противном случае это уже должно быть дело.
для ASP.NET ядро 2.0, Entity Framework Core 2.0, AspNetCore.Identity 2.0 api (https://github.com/kkagill/ContosoUniversity-Backend):
The
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, }); }ответ:
хотя ответ Адриена правильный, вы можете сделать это все в одной строке. Нет необходимости в дополнительной функции или беспорядок.
он работает я проверил его ASP.NET ядро 1.0
var user = await _userManager.GetUserAsync(HttpContext.User);тогда вы можете получить другие свойства переменной, такие как
user.Email. Надеюсь, это кому-то поможет.
вы должны импортировать Microsoft.AspNetCore.система идентификации.Безопасность.Претензии
// to get current user ID var userId = User.FindFirstValue(ClaimTypes.NameIdentifier); // to get current user info var user = await _userManager.FindByIdAsync(userId);
обновление внутри ASP.NET ядро 2.1:
в контроллере:
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.AddSingleton<IHttpContextAccessor, HttpContextAccessor>(); }
пользователей.Тождественность.GetUserId();
не существует в asp.net identity core 2.0. в этом плане я справился по-другому. я создал общий класс для использования всего приложения, из-за получения информации о пользователе.
создать общий класс PCommon & интерфейс IPCommon добавление ссылки
using System.Security.Claimsusing 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)); } } }получить идентификатор пользователя и имя в insert действие
_iPCommon.GetUserId();спасибо, Максуд
на
APiControllerUser.FindFirst(ClaimTypes.NameIdentifier).Valueчто-то вроде этого вы получите претензии
Если вы хотите это в ASP.NET контроллер MVC, используйте
using Microsoft.AspNet.Identity; User.Identity.GetUserId();вам нужно добавить
usingзаявление, потому чтоGetUserId()не будет без него.

Comments