在视图中获取ASP.NET标识当前用户

问题描述 投票:13回答:4

我使用ASP.NET Identity 2.0和MVC。我需要在视图中记录用户的姓名,姓氏,电子邮件等。怎么能得到它?我可以得到@ User.Identity,但没有我的用户类的属性。

//in my view, i need here my ApplicationUser class
<div>
@User.Identity.Name
</div>

//ApplicationUser class
public class ApplicationUser : IdentityUser<int, CustomUserLogin, CustomUserRole,
CustomUserClaim> 
{
    public ApplicationUser()
    {
        this.CreatedDate = DateTime.Now;
    }

    public DateTime CreatedDate { get; set; }

    public string Name { get; set; }

    public string Surname { get; set; }

    public string TaxOffice { get; set; }
}
c# asp.net asp.net-mvc asp.net-identity-2
4个回答
18
投票

如果只需要获取特定属性,则可以在ApplicationUser类中将它们添加为声明,如下例所示:

public async Task<ClaimsIdentity> GenerateUserIdentityAsync(UserManager<ApplicationUser, int> 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));
    // or use the ClaimTypes enumeration
    return userIdentity;
}

这从Startup.Auth类连接起来:

    SessionStateSection sessionStateSection = ConfigurationManager.GetSection("system.web/sessionState") as SessionStateSection;
    app.UseCookieAuthentication(new CookieAuthenticationOptions
    {
        AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
        LoginPath = new PathString("/account/login"),
        CookieName = sessionStateSection.CookieName + "_Application",
        Provider = new CookieAuthenticationProvider
        {
            // Enables the application to validate the security stamp when the user logs in.
            OnValidateIdentity = SecurityStampValidator.OnValidateIdentity<ApplicationUserManager, ApplicationUser, int>
                (
                     validateInterval: TimeSpan.FromMinutes(30),
                     regenerateIdentityCallback: (manager, user) => user.GenerateUserIdentityAsync(manager),
                     getUserIdCallback: (id) => (id.GetUserId<int>())
                ) 

        }
    });

然后,您可以访问声明(在视图或控制器中):

var claims = ((System.Security.Claims.ClaimsIdentity)User.Identity).Claims;
var claim = claims.SingleOrDefault(m => m.Type == "FullName");

这里没有表单身份验证票

如果您希望提供完整的用户详细信息,则可以始终创建如下所示的扩展方法:

public static ApplicationUser GetApplicationUser(this System.Security.Principal.IIdentity identity)
{
    if (identity.IsAuthenticated)
    {
        using (var db = new AppContext())
        {
            var userManager = new ApplicationUserManager(new ApplicationUserStore(db));
            return userManager.FindByName(identity.Name);
        }
    }
    else
    {
        return null;
    }        
}

并称之为:

@User.Identity.GetApplicationUser();

但是,如果你这次打电话,我会建议缓存。


4
投票

有两种方法可以实现这一目标。

1)通过继承CustomPrincipal接口创建自己的IPrincipal,使用Name示例或Surname来包含Emailthisthis

2)直接从数据库获取详细信息并将其作为模型传递给视图。

如果要在多个视图中使用相同的用户详细信息,方法一将是不错的选择,但方法二是实现此目的的最简单方法。如果您需要第二种方法的任何代码帮助,请告诉我。


3
投票

如果您使用.NET Core应用程序:

您可以轻松使用@inject功能调用来注入UserManagerSignInManager

在您的视图中添加以下内容:

@inject SignInManager<YourUserIdentity> SignInManager
@inject UserManager<YourUserIdentity> UserManager

注射后,您应该能够使用UserManagerSignInManager方法。例如:

@if (SignInManager.IsSignedIn(User))
{
    <a asp-area="" asp-controller="Manage" asp-action="Index" title="Manage">Hello @UserManager.GetUserName(User)</a>
}
else
{
}

当需要引用当前登录用户时,请注意传递User对象。

希望这对任何人都很方便:)


0
投票

从您必须使用的控制器获取有关用户的信息

User.Identity.GetUserId();

或者如果您想获得有关您班级内用户的信息

HttpContext.Current.User.Identity.GetUserId();
© www.soinside.com 2019 - 2024. All rights reserved.