User.Identity.Name full name mvc5



我已经通过在 IdentityUser派生的ApplicationUser类中添加几个字段来扩展ASP Net Identity模式。我添加的字段之一是FullName

现在,当我编写 User.Identity.Name时,它给了我用户名,我正在寻找诸如 User.Identity.FullName之类的东西,应该返回我添加的全名。

不确定,如何实现任何指导。

谢谢。

在"应用程序器类"中,您会注意到评论(如果使用标准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;
    }
}

使用此功能,当某人登录时,全名索赔将放在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 "";
    }

并这样使用助手:

@using HelperNamespace
...
@Html.ActionLink("Hello " + User.GetFullName() + "!", "Index", "Manage", routeValues: null, htmlAttributes: new { title = "Manage" })

请注意,自定义用户索赔存储在cookie中,这是从数据库中获取用户信息的优点...为常用数据保存DB命中。

您可以在创建用户时将其添加到用户的索赔中,然后从用户中检索它。

await userManager.AddClaimAsync(user.Id, new Claim("FullName", user.FullName));

重述:

((ClaimsIdentity)User.Identity).FindFirst("FullName")

,或者您只需获取用户并将其从用户访问。

var user = await userManager.FindById(User.Identity.GetUserId())
return user.FullName

我发现这很好

AccountController:

private async Task SignInAsync(ApplicationUser user, bool isPersistent)
    {
        AuthenticationManager.SignOut(DefaultAuthenticationTypes.ExternalCookie);
        var identity = await UserManager.CreateIdentityAsync(user, DefaultAuthenticationTypes.ApplicationCookie);
        identity.AddClaim(new Claim("FullName", user.FullName));
        identity.AddClaim(new Claim("Email", user.Email));
        identity.AddClaim(new Claim("DateCreated", user.DateCreated.ToString("MM/dd/yyyy")));
        AuthenticationManager.SignIn(new AuthenticationProperties() { IsPersistent = isPersistent }, identity);
    }

标识上的扩展方法:

 public static class GenericPrincipalExtensions
{
    public static string FullName(this IPrincipal user)
    {
        if (user.Identity.IsAuthenticated)
        {
            ClaimsIdentity claimsIdentity = user.Identity as ClaimsIdentity;
            foreach (var claim in claimsIdentity.Claims)
            {
                if (claim.Type == "FullName")
                    return claim.Value;
            }
            return "";
        }
        else
            return "";
    }
}

在您的视图中:

 @Html.ActionLink("Hello " + User.FullName() + "!", "Manage", "Account", routeValues: null, htmlAttributes: new { title = "Manage" })

您可以在这里查看线程:链接

可以通过定义您自己的IIdentity(可能也可能是IPrincipal)并在为HTTP请求创建IPrincipal时构建此方法(当提高PostauthentIcateRequest时)。

如何实现自己的IIDentityIPrincipal:如何在ASP.NET MVC中实现自定义主体和身份?

存储价值以索赔并阅读。

商店值

public class ApplicationUser : IdentityUser
{
    public string FullName { get; set; }
    public async Task<ClaimsIdentity> GenerateUserIdentityAsync(UserManager<ApplicationUser> manager)
    {
        var userIdentity = await manager.CreateIdentityAsync(this, DefaultAuthenticationTypes.ApplicationCookie);
        userIdentity.AddClaim(new Claim("FullName", this.FullName));
        return userIdentity;
    }
}

读取值

var FullName = "";
if (User != null)
{
    var identity = (System.Security.Claims.ClaimsIdentity)Context.User.Identity;
    var claim1 = identity.Claims.FirstOrDefault(c => c.Type == "FullName");
    if (claim1 != null)
    {
        FullName = claim1.Value;
    }
}

我通过以下操作解决了问题:

1-通过扩展Iprincipal

来创建自己的自定义普通

2-对每个请求进行身份验证后加载自定义普通。

创建我自己的自定义Principal

interface ICustomPrincipal : IPrincipal
{
    string UserId { get; set; }
    string FirstName { get; set; }
    string LastName { get; set; }
    int CustomerId { get; set; }
}
public partial class CustomPrincipal : ClaimsPrincipal, ICustomPrincipal
{
    #region IPrincipal Members
    public new ClaimsIdentity Identity { get; private set; }
    public new bool IsInRole(string role)
    {
        IdentityManager manager = new IdentityManager();
        return manager.IsInRole(role, this.UserId);
    }
    #endregion
    public CustomPrincipal(ApplicationUser user, IIdentity identity)
        :base(identity)
    {
        this.Identity = new ClaimsIdentity(identity);
        this.UserId = user.Id;
        this.FirstName = user.FirstName;
        this.LastName = user.LastName;
        this.CustomerId = user.CustomerId;
        this.DateCreated = user.DateCreated;
    }
    #region ICustomPrinicpal Members
    public string UserId { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public int CustomerId { get; set; }
    public DateTime DateCreated { get; set; }
    #endregion
    public string GetFullName()
    {
        return this.FirstName + " " + this.LastName;
    }
}

在认证每个请求后加载自定义普通

在global.asax.cs ...

    protected void Application_PostAuthenticateRequest(object sender, EventArgs e)
    {
        if (User.Identity.IsAuthenticated)
        {
            //At this point we need to get the user from the database based on the username. 
            ApplicationUser AppUser = ApplicationUserDB.GetByUserName(User.Identity.Name);
            CustomPrincipal UserPrincipal = new CustomPrincipal(AppUser, User.Identity);
            HttpContext.Current.User = UserPrincipal;
        }
    }

您在上面的代码中看到,我检索了ApplicationUser并将其传递到CustomPrincipal的构造函数中。然后,我将新的CustomPrincipal分配给当前上下文。

这应该做技巧:

User.Claims.Single(x => x.Type== "name").Value

我尝试过,它起作用!

IdentityModels.cs/applicationuser类

// Add custom user claims here
        userIdentity.AddClaim(new Claim("FullName", this.FullName));

_loginPartialView

    <li>
@Html.ActionLink("Hello " +  (((ClaimsIdentity)User.Identity).FindFirst("FullName").Value) + " !", "Index", "Manage", routeValues: null, htmlAttributes: new { title = "Manage" })
    </li>

相关内容

  • 没有找到相关文章

最新更新