Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I get the full name of a user in .net MVC 3 intranet app?

I have an MVC 3 intranet application that performs windows authentication against a particular domain. I would like to render the current user's name.

in the view,

@User.Identity.Name  

is set to DOMAIN\Username, what I want is their full Firstname Lastname

like image 478
Charles Ma Avatar asked Jan 17 '12 19:01

Charles Ma


People also ask

How do I log into MVC identity with email instead of UserName?

cs change the property Email to UserName , remove the [EmailAddress] annotation from there and change the [Display(Name = "Email")] to [Display(Name = "Login")] or something you want to display. If you want to keep Email property, then add UserName property to the same view model and make it as required.


1 Answers

You can do something like this:

using (var context = new PrincipalContext(ContextType.Domain)) {     var principal = UserPrincipal.FindByIdentity(context, User.Identity.Name);     var firstName = principal.GivenName;     var lastName = principal.Surname; } 

You'll need to add a reference to the System.DirectoryServices.AccountManagement assembly.

You can add a Razor helper like so:

@helper AccountName()     {         using (var context = new PrincipalContext(ContextType.Domain))     {         var principal = UserPrincipal.FindByIdentity(context, User.Identity.Name);         @principal.GivenName @principal.Surname     } } 

If you indend on doing this from the view, rather than the controller, you need to add an assembly reference to your web.config as well:

<add assembly="System.DirectoryServices.AccountManagement" /> 

Add that under configuration/system.web/assemblies.

like image 54
vcsjones Avatar answered Sep 29 '22 17:09

vcsjones