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

前端 未结 4 785
南方客
南方客 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 14:54

    If you have many controllers then using @vcsjones approach might be painfull. Therefore I'd suggest creating extension method for TIdentity.

    public static string GetFullName(this IIdentity id)
        {
            if (id == null) return null;
    
            using (var context = new PrincipalContext(ContextType.Domain))
            {
                var userPrincipal = UserPrincipal.FindByIdentity(context, id.Name);
                return userPrincipal != null ? $"{userPrincipal.GivenName} {userPrincipal.Surname}" : null;
            }
        }
    

    And then you can use it in your view:

    Hello, @User.Identity.GetFullName()!

提交回复
热议问题