C# 向ApplicationUser的子类添加声明
在我的MVC应用程序中,我使用创建了基本ASP IdentityC# 向ApplicationUser的子类添加声明,c#,asp.net-mvc,entity-framework,asp.net-identity,C#,Asp.net Mvc,Entity Framework,Asp.net Identity,在我的MVC应用程序中,我使用创建了基本ASP IdentityApplicationUser类的两个子类,并希望向对象添加一些声明,以允许我在视图中轻松显示子类的属性 我肯定错过了一个简单的技巧/对ASP身份设置有一个基本的误解,但我不知道如何做到这一点 将声明添加到ApplicationUser类将很简单,但是在子类中不能重写执行此操作的GenerateUserIdentityAsync方法,以允许我在子类中执行此操作 有没有一种方法可以简单地实现这一点(因为此设置的其他一切都很好地工作),
ApplicationUser
类的两个子类,并希望向对象添加一些声明,以允许我在视图中轻松显示子类的属性
我肯定错过了一个简单的技巧/对ASP身份设置有一个基本的误解,但我不知道如何做到这一点
将声明添加到ApplicationUser
类将很简单,但是在子类中不能重写执行此操作的GenerateUserIdentityAsync
方法,以允许我在子类中执行此操作
有没有一种方法可以简单地实现这一点(因为此设置的其他一切都很好地工作),或者我必须设置我的两个ApplicationUser
子类以直接从IdentityUser
继承,并在IdentityConfig.cs
中为它们设置两组配置
我所说的课程如下:
//The ApplicationUser 'base' class
public class ApplicationUser : IdentityUser
{
public string FirstName { get; set; }
public string LastName { get; set; }
public string ProfilePicture { 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
//** can add claims without any problems here **
userIdentity.AddClaim(new Claim(ClaimTypes.Name, String.Format("{0} {1}", this.FirstName, this.LastName)));I
return userIdentity;
}
}
您可以在ApplicationUser中将GenerateUserIdentityAsync设置为虚拟方法,这将允许您在具体类型中重写实现
这是我能看到的最干净的选项。不过我想在两个子类中添加属性声明,这在基类中是不可用的,如果我没有很好地描述的话,很抱歉。是的,我明白你的意思。能否在基类中使GenerateUserIdentityAsync虚拟,然后在具体类中重写?最好是将其抽象化,但我怀疑您不能这样做,因为ApplicationUser实现了IdentityUserBrilliant,是的,当然就是这样。我脑子里想的是,
GenerateUserIdentityAsync
方法是IdentityUser接口的一部分,无法更改,我承认我以前没有以这种方式使用虚拟修饰符(只是抽象的),所以可能根本不会想到这一点,非常感谢!(如果你想修改你的答案,改为建议,我将接受并投票)
public class MyUserType1 : ApplicationUser
{
[DisplayName("Job Title")]
public string JobTitle { get; set; }
//** How do I add a claim for JobTitle here? **
}
public class MyUserType2 : ApplicationUser
{
[DisplayName("Customer Name")]
public string CustomerName { get; set; }
//** How do I add a claim for CustomerName here? **
}