Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get the ApplicationUser in a controller

I am googleing for get the application user in a controller in ASP.NET Identity 3.0 but I only find results for 5 and lower.

I am trying to get the ApplicationUser properties but I can't get the ApplicationUser at all. I guess it is easy because I am the only one with this problem.

using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNet.Mvc;
using Microsoft.AspNet.Mvc.Rendering;
using Microsoft.Data.Entity;
using System;
using System.Collections.Generic;
using System.Reflection;
using Microsoft.AspNet.Identity;
using System.Security.Claims;

namespace ApplicationUserFMLTest.Controllers
{
    public class CustomClassController : Controller
    {
        private readonly UserManager<ApplicationUser> _userManager;
        private readonly SignInManager<ApplicationUser> _signInManager;

        private ApplicationDbContext _context;

        public CandidatesController(ApplicationDbContext context, UserManager<ApplicationUser> userManager, SignInManager<ApplicationUser> signInManager)
        {
            _context = context;
            _userManager = userManager;
            _signInManager = signInManager;
        }

        // GET: CustomClass
        public async Task<IActionResult> Index()
        {
            ApplicationUser currentUser = _userManager.FindByIdAsync(User.Identity.GetUserId()).Result;


            if (currentUser.PropBool)
                return View(currentUser);


            return View();
        }

        // ManageController function
        private async Task<ApplicationUser> GetCurrentUserAsync()
        {
            return await _userManager.FindByIdAsync(HttpContext.User.GetUserId());
        }

    }
}
like image 662
StuiterSlurf Avatar asked Jan 05 '23 08:01

StuiterSlurf


2 Answers

Joe's answer will work fine, but note there's also a simpler method, that directly takes a ClaimsPrincipal instance and calls GetUserId internally:

var user = await _userManager.GetUserAsync(User);
like image 52
Kévin Chalet Avatar answered Jan 13 '23 13:01

Kévin Chalet


you should change your code like this:

public async Task<IActionResult> Index()
{
    var userId = _userManager.GetUserId(User);
    ApplicationUser currentUser = await _userManager.FindByIdAsync(userId);


    if (currentUser.PropBool)
        return View(currentUser);


    return View();
}

the way to get the userid changed back in RC2

like image 41
Joe Audette Avatar answered Jan 13 '23 13:01

Joe Audette