User.Identity.Name полное имя mvc5

Я расширил схему идентификации ASP NET, добавив несколько полей в класс ApplicationUser, который получен из IdentityUser. Одним из полей, которые я добавил, является FullName.

Теперь, когда я пишу User.Identity.Name, он дает мне имя пользователя, я ищу что-то вроде User.Identity.FullName, которое должно вернуть добавленное FullName.

Не уверен, как это может быть достигнуто, любые рекомендации должны быть высоко оценены.

Спасибо.

Ответы

Ответ 1

Вы можете добавить его к претензиям Пользователя при создании пользователя, а затем получить его как заявку от User.Identity:

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

Извлеките его:

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

Или вы можете просто получить пользователя и получить его от пользователя. FullName напрямую:

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

Ответ 2

В классе 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 "";
    }

И используйте помощник следующим образом:

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

Обратите внимание, что пользовательские претензии пользователя хранятся в файле cookie, и это предпочтительнее, чтобы получить информацию о пользователе из БД... сохраняет снимок БД для общедоступных данных.

Ответ 3

Я обнаружил, что это работает очень хорошо

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

Вы можете посмотреть здесь: Ссылка

Ответ 5

Я решил проблему, выполнив следующие действия:

1 - Создайте свой собственный CustomPrincipal, расширив IPrincipal

2 - Загрузите 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;
    }
}

Загрузите CustomPrincipal после аутентификации каждого запроса

В файле 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 текущему контексту.