Reputation: 27
In my ASP.NET Core web application, I added custom fields in my Identity such as CompanyCode
using ApplicationUser
model. I am now trying to retrieve the CompanyCode
of the current logged in user in the web application, but I do not know how to access this field. How can this be done?
Upvotes: 0
Views: 612
Reputation: 21363
From your description, I suppose you have already added the CompanyCode to the ApplicationUser model, and configured the service and UserManager to use the ApplicationUser model. Like this:
UserManager:
private readonly UserManager<ApplicationUser> _userManager;
private readonly SignInManager<ApplicationUser> _signInManager;
Setup.cs ConfigureServices:
services.AddDefaultIdentity<ApplicationUser>(options => options.SignIn.RequireConfirmedAccount = true)
.AddEntityFrameworkStores<ApplicationDbContext>();
Then, you could try to access the CompanyCode field by using the following code:
@UserManager.GetUserAsync(User).Result.CompanyCode
For example:
In the _LoginPartial.cshtml page:
<li class="nav-item">
<a class="nav-link text-dark" asp-area="Identity" asp-page="/Account/Manage/Index" title="Manage">Hello @User.Identity.Name! @UserManager.GetUserAsync(User).Result.CompanyCode</a>
</li>
After login, the result as below:
Or, in the controller action method:
private readonly ILogger<HomeController> _logger;
private readonly UserManager<ApplicationUser> _userManager;
public HomeController(ILogger<HomeController> logger, UserManager<ApplicationUser> usermanager)
{
_logger = logger;
_userManager = usermanager;
}
public IActionResult Index()
{
if (this.User.Identity.IsAuthenticated)
{
//login success
var item = _userManager.GetUserAsync(this.User).Result.CompanyCode;
}
return View();
}
The result like this:
Upvotes: 2