我有一个使用 Windows 身份验证设置的 Intranet 应用程序。 我需要在标题中显示用户名和用户的姓名首字母,例如:
Welcome jSmith JS
到目前为止我做了什么:
<div class="header__profile-name">Welcome <b>@User.Identity.Name.Split('\\')[1]</b></div>
<div class="header__profile-img">@User.Identity.Name.Split('\\')[1].Substring(0, 2)</div>
问题是用户名不是总是名字的第一个字母 + 姓氏,有时用户名可以是名字 + 姓氏的第一个字母,例如:
John Smith - the username can be jsmith but sometimes it can also be: johns
在这种情况下,我的代码是错误的,因为它会导致:
jo instead of js
如何获取完整的用户名:User.identity
的名字和姓氏?
然后我将我的代码基于完整的用户名(名字和姓氏)以设置首字母缩写,而不是始终一致的用户名。
最佳答案
在 ApplicationUser 类中,您会注意到一条注释(如果您使用标准 MVC5 模板),上面写着“在此处添加自定义用户声明”。
鉴于此,添加 FullName 的效果如下:
public class ApplicationUser : IdentityUser
{
public string FullName { get; set; }
public async Task<ClaimsIdentity> GenerateUserIdentityAsync(UserManager<ApplicationUser> manager)
{
// Note the authenticationType must match the one defined in CookieAuthenticationOptions.AuthenticationType
var userIdentity = await manager.CreateIdentityAsync(this, DefaultAuthenticationTypes.ApplicationCookie);
// Add custom user claims here
userIdentity.AddClaim(new Claim("FullName", this.FullName));
return userIdentity;
}
}
使用这个,当有人登录时,FullName 声明将被放入 cookie 中。您可以像这样创建一个助手来访问它:
public static string GetFullName(this System.Security.Principal.IPrincipal usr)
{
var fullNameClaim = ((ClaimsIdentity)usr.Identity).FindFirst("FullName");
if (fullNameClaim != null)
return fullNameClaim.Value;
return "";
}
更新
或者您可以在创建用户时将其添加到用户的声明中,然后从 User.Identity 中将其作为声明检索:
await userManager.AddClaimAsync(user.Id, new Claim("FullName", user.FullName));
取回它:
((ClaimsIdentity)User.Identity).FindFirst("FullName")
或者您可以直接获取用户并从 user.FullName 中访问它:
var user = await userManager.FindById(User.Identity.GetUserId())
return user.FullName
更新
对于 intranet
你可以这样做:
using (var context = new PrincipalContext(ContextType.Domain))
{
var principal = UserPrincipal.FindByIdentity(context, User.Identity.Name);
var firstName = principal.GivenName;
var lastName = principal.Surname;
}
您需要添加对 System.DirectoryServices.AccountManagement
程序集的引用。
您可以像这样添加 Razor 助手:
@helper AccountName()
{
using (var context = new PrincipalContext(ContextType.Domain))
{
var principal = UserPrincipal.FindByIdentity(context, User.Identity.Name);
@principal.GivenName @principal.Surname
}
}
如果您打算从 View 而不是 Controller 执行此操作,则还需要将程序集引用添加到您的 web.config:
<add assembly="System.DirectoryServices.AccountManagement" />
在 configuration/system.web/assemblies
下添加。
关于c# - 获取 User.identity 的名字和姓氏,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51943909/