c# - 获取 View 中的当前用户的 ASP.NET 标识

标签 c# asp.net asp.net-mvc asp.net-identity-2

我使用 ASP.NET Identity 2.0 和 MVC。我需要在 View 中记录用户的姓名、姓氏、电子邮件等。怎么才能得到呢?我只能得到 @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; }
}

最佳答案

如果您只需要获取特定的属性,您可以将它们作为声明添加到您的 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>())
                ) 

        }
    });

然后,您可以访问声明(在 View 或 Controller 中):

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

但是,如果您一直调用它,我会建议缓存。

关于c# - 获取 View 中的当前用户的 ASP.NET 标识,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27139068/

相关文章:

c# - Entity Framework 在加载 DynamicProxies 时挂起

.net - 更新面板复制了我的控件

javascript - 如何从部分加载的 aspx 页面的代码隐藏中调用 javascript 函数

javascript - 使用 CKEditor 自定义文件浏览器并使用 ASP.Net MVC 上传

asp.net - IDENTITY_INSERT 设置为关闭错误

jquery - 如何将 JSON 对象传递给 MVC 操作参数?

c# - 代码契约(Contract) : How do I state in a post-condition that a field/property's value has not changed?

c# - 获取IPEndPoint的动态分配端口

c# - PushSharp APNS 反馈服务示例

c# - 更好的 Dispose 方法(通过 ComponentModel.IContainer ??)