2016-04-28 37 views
1

在我的MVC應用程序中,我使用TPT inheritance創建了兩個基本ASP標識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; 
    } 
} 

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? ** 
} 

回答

3

您可以GenerateUserIdentityAsync在ApplicationUser一個虛擬的方法,這將允許您覆蓋在你的具體類型的實現。

這是我能看到的最乾淨的選項。

+0

我想爲兩個子類中的屬性添加聲明,但這些聲明在基類中不可用,如果我沒有很好地描述它,則很抱歉。 – Ted

+1

是的,我明白你的意思。您可以在基類中創建GenerateUserIdentityAsync虛擬,然後在具體類中重寫?更好的辦法是將其抽象化,但我懷疑你不能這樣做,因爲ApplicationUser實現了IdentityUser –

+1

輝煌,當然就是這樣。我在腦海中曾經說過,GenerateUserIdentityAsync方法是IdentityUser接口的一部分,無法更改,我承認我之前沒有以這種方式使用虛擬修飾符(只是抽象的),所以可能不會無論如何都有這個想法,非常感謝! (如果你想編輯你的答案,而不是提示,我會接受和upvote) – Ted