6

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

    }
}
2
  • What is the problem with your code? Did you get an error? Sep 17, 2016 at 9:14
  • It says that Identity does not contain a definition for 'GetUserId' and te best extention method ovreload 'PrincipalExtensions.GetUserId(ClaimsPrincipal)' requires a receiver of type 'ClaimsPrincipal' Sep 17, 2016 at 9:47

2 Answers 2

8

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

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.