2015-12-02 79 views
0

我已经实现了ASP.Net身份的自定义原则,但是当我尝试让我的从HttpContext.Current.User我收到下面的异常定制的原则:自定义ASP.Net原则 - 无法转换'System.Security.Principal.GenericPrincipal'类型的对象来键入'Business.ICustomPrincipal'

无法投类型的对象System.Security.Principal.GenericPrincipal为键入“VenuePortal.Business.ICustomPrincipal”。

我的实现是:在这个Ninject

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); 
    } 
} 

错误抛出结合:

kernel.Bind<ICustomPrincipal>().ToMethod(context => (ICustomPrincipal)HttpContext.Current.User).InRequestScope(); 

我有这同样的解决方案,另一个(以上)的项目,所以我猜有工作是什么影响这种框架的变化? HttpContext.Current.User仍似乎返回原理所以不应该这一切工作?

任何帮助非常感谢。

回答

1

HttpContext.Current.User确实实现了IPrincipal,如果您使用的是Asp.Net Identity框架,此背后的对象通常是GenericPrincipal。而GenericPrincipal是.Net框架的一部分,它不能实现你的ICustomPrincipal接口。

如果您正在寻找扩展方法User对象来拉出额外的数据,有几种不同的方法(使用声明是其中之一)。但是创建你自己的CustomPrincipal已成为过去,现在有更简单的方法来做到这一点。

+0

真的,这很有趣。我将不得不做一些研究。感谢您的回应。 – Simon

+0

这很有趣,我可以建议你指出一些其他方法可能是什么吗? –

0

我发现,这是当未登录用户造成我发现两个解决办法:

  1. 时不要在 没有登录的注入当前用户(相当在这个例子中简单,因为我刚刚从我的LoginController中删除了 的属性。
  2. 注入一个处理返回当前用户的工厂类,无论用户是否登录,Ninject都能够实例化并注入它。工厂类处理任何空例外等。

我希望这可以帮助别人。

相关问题