我已经为我的MVC项目开发了一个简单的IIdentity和IPrincipal,我想覆盖User和User.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以同样的方式返回我的自定义标识类型?
发布于 2012-11-20 23:25:11
您可以在MyPrincipal类中显式实现IPrincipal,并添加您自己的MyIdentity类型的Identity属性。
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();
}
}发布于 2012-11-20 23:13:49
您正在请求一些没有显式强制转换就无法完成的任务
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属性最好存储用户ID,在本例中,它看起来是一个GUID。
https://stackoverflow.com/questions/13475837
复制相似问题