2

Я новичок в мире ASP.NET. Смог сделать авторизацию через логин/пароль.

AccountViewModels.cs

 public class LoginViewModel
    {
        [Required]
        [Display(Name = "User Name")]
        public string UserName { get; set; }
...

AccountController.cs

...
        public async Task<ActionResult> Login(LoginViewModel model, string returnUrl)
        {
            if (!ModelState.IsValid)
            {
                return View(model);
            }
            var result = await SignInManager.PasswordSignInAsync(model.UserName, model.Password, model.RememberMe, shouldLockout: false);
...

Но как мне теперь получить имя, авторизовавшегося пользователя (UserName)? К примеру, чтобы затем получить относящиеся к нему записи из базы данных?

Полязив по SO, нашел тему и с помощью кода оттуда хотел просто хотя бы вывести UserName в консоль:

public ActionResult Index()
{
    var claimsIdentity = User.Identity as ClaimsIdentity;
    if (claimsIdentity != null)
    {
        // the principal identity is a claims identity.
        // now we need to find the NameIdentifier claim
        var userIdClaim = claimsIdentity.Claims
            .FirstOrDefault(x => x.Type == ClaimTypes.NameIdentifier);

        if (userIdClaim != null)
        {
            var userIdValue = userIdClaim.Value;
            Console.WriteLine(userIdValue.ToString());
        }
    }

    return View();
}

Но в консоле так и ничего не появилось.

1 ответ 1

2

В userIdValue храниться ID. А мне нужно было свойство UserName, которое храниться в User.Identity.Name. После этого обнаружения дальше все конечно же пошло по накатанной. Я передал это имя во View через ViewBag:

public ActionResult Index2()
{
    var claimsIdentity = User.Identity as ClaimsIdentity;
    if (claimsIdentity != null)
    {
        var userIdClaim = claimsIdentity.Claims
            .FirstOrDefault(x => x.Type == ClaimTypes.NameIdentifier);

        if (userIdClaim != null)
        {
            var userIdValue = userIdClaim.Value;
            ViewBag.UserName = User.Identity.Name;
        }
    }

    return View();
}

Ваш ответ

By clicking “Отправить ответ”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.