2012-11-20 54 views
5
的IIdentity的財產

我已經開發出一種簡單IIdentityIPrincipal我的MVC項目,我想重寫UserUser.Identity與正確的類型覆蓋用戶

這裏返回值是我的自定義身份:

public class MyIdentity : IIdentity 
{ 
    public MyIdentity(string name, string authenticationType, bool isAuthenticated, Guid userId) 
    { 
     Name = name; 
     AuthenticationType = authenticationType; 
     IsAuthenticated = isAuthenticated; 
     UserId = userId; 
    } 

    #region IIdentity 
    public string Name { get; private set; } 
    public string AuthenticationType { get; private set; } 
    public bool IsAuthenticated { get; private set; } 
    #endregion 

    public Guid UserId { get; private set; } 
} 

這裏是我的自定義校長:

public class MyPrincipal : IPrincipal 
{ 
    public MyPrincipal(IIdentity identity) 
    { 
     Identity = identity; 
    } 


    #region IPrincipal 
    public bool IsInRole(string role) 
    { 
     throw new NotImplementedException(); 
    } 

    public IIdentity Identity { get; private set; } 
    #endregion 
} 

這裏是我的自定義控制器,我已成功更新User屬性返回我的自定義主要的類型:

public abstract class BaseController : Controller 
{ 
    protected new virtual MyPrincipal User 
    { 
     get { return HttpContext == null ? null : HttpContext.User as MyPrincipal; } 
    } 
} 

我如何能做到用同樣的方式爲User.Identity返回我的自定義身份類型?

+0

你在哪裏設置你的自定義主體在HttpContext? –

+0

在我的global.asax.cs Application_AuthenticateRequest方法 – Swell

回答

3

您可以在您的MyPrincipal類中明確實施IPrincipal,並添加您自己的類型的屬性。

public class MyPrincipal : IPrincipal 
{ 
    public MyPrincipal(MyIdentity identity) 
    { 
     Identity = identity; 

    } 

    public MyIdentity Identity {get; private set; } 

    IIdentity IPrincipal.Identity { get { return this.Identity; } } 

    public bool IsInRole(string role) 
    { 
     throw new NotImplementedException(); 
    } 
} 
+0

請您仔細檢查您的代碼,我看不出如何解決它。謝謝 – Swell

+0

@Swell - 打錯了。 – Joe

+0

我想我明白這一行:「IIdentity IPrincipal.Identity {get {return this.Identity;}}」,但這是我第一次看到類似的東西。你能解釋一下如何解釋它嗎? TIA – Swell

1

你問的東西,不能沒有一個明確的轉換

public class MyClass 
{ 
    private SomeThing x; 
    public ISomeThing X { get { return x; } } 
} 

當你調用MyClass.X來完成,你會得到一個ISomeThing,而不是SomeThing。你可以做一個明確的演員,但這有點笨拙。

MyClass myClass = new MyClass(); 
SomeThing someThing = (SomeThing)(myClass.X); 

理想情況下,您爲IPrincipal.Name存儲的值將是唯一的。如果「jdoe」在您的應用程序中不是唯一的,那麼您的IPrincipal.Name屬性在存儲用戶標識時會更好。在你的情況下,這似乎是一個GUID。

+0

我想爲MyPrincipal用戶做一個明確的轉換。我想將User.Identity的返回類型轉換爲MyIdentity – Swell