Reputation: 1372
I tried to get current user details from Windows Active Directory using a .NetCore C# web application but I couldn't show them. I tried debugging and I have confirmed that my code already connected with my domain, because I could ensure my username and email details in debugging mode.
Here's my "Index.cshtml.cs" file
namespace Employees.Pages
{
public class IndexModel : PageModel
{
public void OnGet()
{
var username = User.Identity.Name;
using (var context =new PrincipalContext(ContextType.Domain, "my Domain"))
{
var user = UserPrincipal.FindByIdentity(context, username);
if (user != null)
{
ViewData["UserName"] = user.Name;
ViewData["EmailAddress"] = user.EmailAddress;
}
}
}
}
And here's my "Index.cshtml" file:
@page
@model IndexModel
@{
ViewData["Title"] = "Home page";
}
<p>@ViewData["EmployeeName"]</p>
Upvotes: 0
Views: 131
Reputation: 88
I could check it in the basic project template when I made it with azure active directory. Check below:
@using System.Security.Claims
@if (User.Identity.IsAuthenticated)
{
var identity = User.Identity as ClaimsIdentity; // Azure AD V2 endpoint specific
string preferred_username = identity.Claims.FirstOrDefault(c => c.Type == "name")?.Value;
It's changed in visual studio 2019. This is what I am using now:
@using System.Security.Principal
<ul class="nav navbar-nav navbar-right loginpartial">
@if (User.Identity.IsAuthenticated)
{
<li class="nav-item">
<span class="navbar-text text-dark">Hello @User.Identity.Name.Substring(0,User.Identity.Name.IndexOf("@"))!</span>
</li>
Upvotes: 1