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());
}
}
}
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);
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With