C# 获取User.identity的名字和姓氏
我使用Windows身份验证设置了一个Intranet应用程序。 我需要在标题中显示用户名和用户的首字母缩写,例如: 欢迎来到jSmithJS 到目前为止我所做的:C# 获取User.identity的名字和姓氏,c#,asp.net-mvc,C#,Asp.net Mvc,我使用Windows身份验证设置了一个Intranet应用程序。 我需要在标题中显示用户名和用户的首字母缩写,例如: 欢迎来到jSmithJS 到目前为止我所做的: <div class="header__profile-name">Welcome <b>@User.Identity.Name.Split('\\')[1]</b></div> <div class="header__profile-img">@User.Identity
<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>
Welcome@User.Identity.Name.Split('\\')[1]
@User.Identity.Name.Split('\\')[1]。子字符串(0,2)
问题是用户名不总是名字的第一个字母+姓氏,有时用户名可以是名字+姓氏的第一个字母,例如:
John Smith-用户名可以是jsmith,但有时也可以是jsmith
be:约翰
在这种情况下,我的代码是错误的,因为它将导致:
jo而不是js
如何使用user.identity
获取完整的用户名:名字和姓氏
然后,我将基于完整的用户名(名字和姓氏)来设置首字母,而不是始终不一致的用户名。在ApplicationUser类中,您会注意到一条注释(如果使用标准MVC5模板),上面写着“在此处添加自定义用户声明” 有鉴于此,添加全名的过程如下所示:
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;
}
}
更新
或您可以在创建用户时将其添加到用户的声明中,然后将其作为声明从用户检索。标识:
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
,您可以执行以下操作:
public static string GetFullName(this System.Security.Principal.IPrincipal usr)
{
var fullNameClaim = ((ClaimsIdentity)usr.Identity).FindFirst("FullName");
if (fullNameClaim != null)
return fullNameClaim.Value;
return "";
}
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
程序集的引用
您可以添加剃须刀辅助对象,如下所示:
@helper AccountName()
{
using (var context = new PrincipalContext(ContextType.Domain))
{
var principal = UserPrincipal.FindByIdentity(context, User.Identity.Name);
@principal.GivenName @principal.Surname
}
}
如果您决定从视图而不是控制器执行此操作,则还需要向web.config添加程序集引用:
<add assembly="System.DirectoryServices.AccountManagement" />
将其添加到
configuration/system.web/assemblies
下面,谢谢您的回答,我在哪里可以找到ApplicationUser
类?我没有创建用户,我使用的是intranet模板。@user3378165您应该将其设置为ApplicationUser:IdentityUser
。但是secend way更好谢谢,我在网上看到了这些答案,但这并不能回答我的问题,我正在使用ready windows身份验证模板,所以我不知道如何操作。@user3378165您想在intranet应用程序中获取用户的全名吗?是的,intranet应用程序具有windows身份验证