Get the ApplicationUser in a controller

asp.net-core c# entity-framework-core identity

Question

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

    }
}
1
3
9/17/2016 9:13:28 AM

Accepted Answer

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);
6
9/17/2016 10:27:37 AM

Popular Answer

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



Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow