asp.net-mvc User.Identity.Name 全名 mvc5

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/21362751/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-08 03:28:51  来源:igfitidea点击:

User.Identity.Name full name mvc5

asp.net-mvcasp.net-identity

提问by Ashish Charan

I've extended the ASP NET identity schema by adding few fields in the ApplicationUserClass which is derived from IdentityUser. One of the field that I've added is FullName.

我通过在ApplicationUser派生自IdentityUser. 我添加的字段之一是FullName.

Now, when I write User.Identity.Name, it gives me the user name, I m looking for something like User.Identity.FullNamewhich should return the FullName that I have added.

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

Not sure, how this can be achieved any guidance shall be greatly appreciated.

不确定,如何实现任何指导将不胜感激。

Thanks.

谢谢。

回答by Hao Kung

You could add it to the User's claims when you create the user and then retrieve it as a claim from the User.Identity:

您可以在创建用户时将其添加到用户的声明中,然后将其作为来自 User.Identity 的声明进行检索:

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

Retreive it:

检索它:

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

Or you could just fetch the user and access it off of the user.FullName directly:

或者你可以直接从 user.FullName 获取用户并访问它:

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

回答by Marcel

In the ApplicationUser class, you'll notice a comment (if you use the standard MVC5 template) that says "Add custom user claims here".

在 ApplicationUser 类中,您会注意到一条注释(如果您使用标准 MVC5 模板),内容为“在此处添加自定义用户声明”。

Given that, here's what adding FullName would look like:

鉴于此,以下是添加 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;
    }
}

Using this, when someone logs in, the FullName claim will be put in the cookie. You could make a helper to access it like this:

使用此功能,当有人登录时,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 "";
    }

And use the helper like this:

并像这样使用助手:

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

Note that custom user claims are stored in the cookie and this is preferable to getting the user info from the DB... saves a DB hit for commonly accessed data.

请注意,自定义用户声明存储在 cookie 中,这比从 DB 获取用户信息更可取...为常用访问的数据保存 DB 命中。

回答by H20rider

I have found that this works pretty well

我发现这很好用

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);
    }

Extension Method on 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 "";
    }
}

In your View:

在您的视图中:

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

You can look at the thread here: Link

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

回答by Pawe? Bejger

It is possible by defining your own IIdentity(and possibly IPrincipaltoo) and constructing this when creating the IPrincipalfor the HTTP request (when PostAuthenticateRequest is raised).

可以通过定义您自己的IIdentity(也可能IPrincipal也是)并在IPrincipal为 HTTP 请求创建 时构造它(当 PostAuthenticateRequest 引发时)。

How to implement your own IIDentityand IPrincipal: How do I implement custom Principal and Identity in ASP.NET MVC?

如何实现您自己的IIDentityIPrincipal如何在 ASP.NET MVC 中实现自定义 Principal 和 Identity?

回答by FrankO

I solved the problem by doing the following:

我通过执行以下操作解决了这个问题:

1 - Create my own CustomPrincipal by extending IPrincipal

1 - 通过扩展 IPrincipal 创建我自己的 CustomPrincipal

2 - Load the CustomPrincipal after each request has been authenticated.

2 - 在每个请求经过身份验证后加载 CustomPrincipal。

Create my own CustomPrincipal

创建我自己的 CustomPrincipal

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;
    }
}

Load the CustomPrincipal after each request has been authenticated

在每个请求通过身份验证后加载 CustomPrincipal

In the Global.asax.cs...

在 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;
        }
    }

As you can see in my code above, I retrieve an ApplicationUserand pass it in the constructor of the CustomPrincipal. I then assign the new CustomPrincipalto the current context.

正如您在上面的代码中看到的那样,我检索 anApplicationUser并将其传递到CustomPrincipal. 然后我将 new 分配给CustomPrincipal当前上下文。

回答by Arun Prasad E S

Store value to claims and read it.

存储索赔的价值并阅读它。

Store Value

存储价值

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;
    }
}

Read Value

读取值

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;
    }
}

回答by user7254918

This should do the trick:

这应该可以解决问题:

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

回答by Joel Céspedes Rosario

I tried this and it works!

我试过了,它有效!

IdentityModels.cs/ApplicationUser Class

IdentityModels.cs/ApplicationUser 类

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

_LoginPartialView

_LoginPartialView

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