2012-11-20 93 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