我想在控制器中获得自定义ApplicationUser
实例。我可以从控制器内的User
对象获取它吗?我该怎么做?
我试过了,但它没有奏效:
ApplicationUser u = (ApplicationUser)User;
ApplicationUser u2 = (ApplicationUser)User.Identity;
我的自定义身份模型是这样的:
public class ApplicationUser : IdentityUser<long, ApplicationUserLogin, ApplicationUserRole, ApplicationUserClaim>
{
public virtual UserInfo UserInfo { get; set; }
public async Task<ClaimsIdentity> GenerateUserIdentityAsync(ApplicationUserManager 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
return userIdentity;
}
}
public class ApplicationRole : IdentityRole<long, ApplicationUserRole>
{
public ApplicationRole() : base() { }
public ApplicationRole(string name, string description)
{
this.Name = name;
this.Description = description;
}
public virtual string Description { get; set; }
}
public class ApplicationUserRole : IdentityUserRole<long> { }
public class ApplicationUserClaim : IdentityUserClaim<long> { }
public class ApplicationUserLogin : IdentityUserLogin<long> { }
答案 0 :(得分:2)
没有。控制器的User属性返回IPrincipal对象,而不是ApplicationUser对象。这是两件完全不同的事情。 ASP.NET使用IPrincipal来控制身份验证和授权,而ApplicationUser只是数据库中使用的实体。
如果您需要ApplicationUser,则必须从UserManager获取它。