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

前端 未结 4 795
南方客
南方客 2020-12-23 14:16

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

4条回答
  •  渐次进展
    2020-12-23 15:07

    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 that under configuration/system.web/assemblies.

提交回复
热议问题