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
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.
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
.
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