Jak uzyskać aktualny identyfikator zalogowanego użytkownika ASP.NET Rdzeń

Robiłem to wcześniej z MVC5 używając User.Identity.GetUserId() ale to chyba nie działa tutaj. User.Identity nie posiada metody GetUserId()

Używam Microsoft.AspNet.Identity

Author: Soren, 2015-06-08

12 answers

Do ASP.NET Core 1.0 RC1 :

To User.GetUserId() z systemu .Ochrona.Claims przestrzeń nazw.

Od ASP.NET Core 1.0 RC2 :

Teraz musisz użyć UserManager . Możesz utworzyć metodę, aby uzyskać bieżącego użytkownika:

private Task<ApplicationUser> GetCurrentUserAsync() => _userManager.GetUserAsync(HttpContext.User);

I uzyskać informacje o użytkowniku za pomocą obiektu:

var user = await GetCurrentUserAsync();

var userId = user?.Id;
string mail = user?.Email;

Uwaga: Można to zrobić bez użycia metody piszącej pojedyncze linie jak Ta string mail = (await _userManager.GetUserAsync(HttpContext.User))?.Email, ale nie respektuje to pojedynczego zasada odpowiedzialności. Lepiej wyizolować sposób, w jaki dostajesz użytkownika, ponieważ jeśli pewnego dnia zdecydujesz się zmienić system zarządzania użytkownikami, np. użyć innego rozwiązania niż tożsamość, będzie to bolesne, ponieważ musisz przejrzeć cały kod.

 82
Author: AdrienTorris,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-03-08 03:45:18

Możesz go pobrać w swoim kontrolerze:

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

Lub napisać metodę rozszerzenia jak wcześniej .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;
        }
    }
}

I get wherever user ClaimsPrincipal is available :

using Microsoft.AspNetCore.Mvc;
using Shared.Web.MvcExtensions;

namespace Web.Site.Controllers
{
    public class HomeController : Controller
    {
        public IActionResult Index()
        {
            return Content(this.User.GetUserId());
        }
    }
}
 49
Author: Soren,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-09-17 07:40:42

I włączone za pomocą systemu.Ochrona.Claims i mogę uzyskać dostęp do metody rozszerzenia GetUserId ()

NB: miałem za pomocą Microsoft.AspNet.Tożsamość już, ale nie mógł uzyskać metody rozszerzenia. Więc myślę, że oba muszą być używane w połączeniu ze sobą

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

Edytuj : Ta odpowiedź jest już nieaktualna. W CORE 1.0 można znaleźć odpowiedź Sorena lub Adriena na datowany sposób osiągnięcia tego w CORE 1.0

 31
Author: MRainzo,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-10-23 09:18:32

Dla. NET Core 2.0 do pobrania identyfikatora użytkownika zalogowanego użytkownika w klasie Controller wymagane są tylko następujące elementy:

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

Lub

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

Np.

contact.OwnerID = this.User.FindFirstValue(ClaimTypes.NameIdentifier);
 15
Author: Oracular Man,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-03-08 06:53:47

Jak napisano gdzieś w tym poście, metoda GetUserId() została przeniesiona do 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);
}

Jeśli uruchomiłeś pusty projekt, być może będziesz musiał dodać użytkownika do swoich usług w startup.cs. W przeciwnym razie powinno to już mieć miejsce.

 10
Author: Menno Guldemond,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-10-22 07:41:02

Dla ASP.NET Core 2.0, Entity Framework Core 2.0, AspNetCore.Identity 2.0 api ( https://github.com/kkagill/ContosoUniversity-Backend):

Id został zmieniony na 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,
        });
    }

ODPOWIEDŹ:

Tutaj wpisz opis obrazka

 5
Author: jv_,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-03-08 10:00:28

Chociaż odpowiedź Adriena jest prawidłowa, możesz zrobić to wszystko w jednej linii. Nie ma potrzeby dodatkowej funkcji ani bałaganu.

To działa sprawdziłem to w ASP.NET Core 1.0

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

Następnie można uzyskać inne właściwości zmiennej, takie jak user.Email. Mam nadzieję, że to komuś pomoże.

 4
Author: Ahmad,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-02-27 18:29:31

Musisz zaimportować Microsoft.AspNetCore.Tożsamość I System.Ochrona.Roszczenia

// to get current user ID
var userId = User.FindFirstValue(ClaimTypes.NameIdentifier);

// to get current user info
var user = await _userManager.FindByIdAsync(userId);
 3
Author: Mansur Haider,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-11-16 03:26:21

Update in ASP.NET Core 2.1:

W kontrolerze:

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

W drugiej klasie:

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

Powinieneś zarejestrować IHttpContextAccessor w klasie startowej w następujący sposób:

public void ConfigureServices(IServiceCollection services)
{
    services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();
}
 3
Author: TanvirArjel,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-09-02 08:13:17

Użytkownik.Tożsamość.GetUserId ();

Nie istnieje w asp.net identity core 2.0. pod tym względem radziłem sobie w inny sposób. stworzyłem wspólną klasę do korzystania z całej aplikacji, ze względu na uzyskiwanie informacji o użytkowniku.

Tworzenie wspólnej klasy PCommon & interface IPCommon dodawanie referencji 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();        
    }    
}

Tutaj Implementacja klasy common

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



    }
}

Get userId and name in insert action

_iPCommon.GetUserId();

Dzięki, Maksud

 0
Author: Maksud,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-08-05 11:15:07

W APiController

User.FindFirst(ClaimTypes.NameIdentifier).Value

Coś takiego dostaniesz roszczenia

 -1
Author: Usman,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-09-03 13:17:52

Jeśli chcesz to w ASP.NET kontroler MVC, użyj

using Microsoft.AspNet.Identity;

User.Identity.GetUserId();

Musisz dodać using oświadczenie, ponieważ GetUserId() nie będzie bez niego.

 -6
Author: Pravin Deshmukh,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-08-21 21:35:30