自定义ASP.Net原则-无法强制转换类型为';System.Security.Principal.GenericPrincipal';输入';Business.ICustomPrincipal';
我已经为ASP.Net标识实现了自定义原则,但是当我尝试从HttpContext.Current.User获取自定义原则时,我收到以下异常: 无法将类型为“System.Security.Principal.GenericPrincipal”的对象强制转换为类型为“VenuePortal.Business.ICustomPrincipal” 我的实施是:自定义ASP.Net原则-无法强制转换类型为';System.Security.Principal.GenericPrincipal';输入';Business.ICustomPrincipal';,asp.net,asp.net-identity,iprincipal,Asp.net,Asp.net Identity,Iprincipal,我已经为ASP.Net标识实现了自定义原则,但是当我尝试从HttpContext.Current.User获取自定义原则时,我收到以下异常: 无法将类型为“System.Security.Principal.GenericPrincipal”的对象强制转换为类型为“VenuePortal.Business.ICustomPrincipal” 我的实施是: public interface ICustomPrincipal : IPrincipal { int UserID { get;
public interface ICustomPrincipal : IPrincipal
{
int UserID { get; set; }
string UserName { get; set; }
string Email { get; set; }
string AuthCode { get; set; }
string Title { get; set; }
}
public class CustomPrincipal : ICustomPrincipal
{
public int UserID { get; set; }
public string UserName { get; set; }
public string Email { get; set; }
public string AuthCode { get; set; }
public string Title { get; set; }
public IIdentity Identity { get; private set; }
public bool IsInRole(string role) { return false; }
public CustomPrincipal(string email)
{
Identity = new GenericIdentity(email);
}
}
此Ninject绑定中出现错误:
kernel.Bind<ICustomPrincipal>().ToMethod(context => (ICustomPrincipal)HttpContext.Current.User).InRequestScope();
kernel.Bind();
我在另一个(较旧的)项目中使用了相同的解决方案,所以我猜是有某种框架变化影响了这一点?HttpContext.Current.User似乎仍然返回一个IPrinciple,所以这一切不都应该工作吗
非常感谢您的帮助。
HttpContext.Current.User
确实是实现了IPrincipal
,如果您使用的是Asp.Net Identity framework,则其背后的对象通常是GenericPrincipal
。而GenericPrincipal
是.Net框架的一部分,它无法实现您的ICustomPrincipal
接口
如果您希望在
User
对象上使用扩展方法来提取额外数据,那么有几种不同的方法(使用声明就是其中之一)。但是创建自己的CustomPrincipal
已经成为过去,现在有了更简单的方法 我发现这是由于用户未登录造成的。我找到了两种解决方案:
我希望这对其他人有帮助。真的,这很有趣。我必须做一些研究。谢谢你的回答。这很有趣,我能建议你指出其他方法可能是什么吗?