【问题标题】:Custom ASP.Net Principle - Unable to cast object of type 'System.Security.Principal.GenericPrincipal' to type 'Business.ICustomPrincipal'自定义 ASP.Net 原则 - 无法将“System.Security.Principal.GenericPrincipal”类型的对象转换为“Business.ICustomPrincipal”类型
【发布时间】:2024-06-15 19:50:01
【问题描述】:

我已经为 ASP.Net 身份实现了一个自定义原则,但是当我尝试从 HttpContext.Current.User 获取我的自定义原则时,我收到以下异常:

无法将“System.Security.Principal.GenericPrincipal”类型的对象转换为“VenuePortal.Business.ICustomPrincipal”类型。

我的实现是:

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

我在另一个(较旧的)项目中也有同样的解决方案,所以我猜有某种框架更改会影响这个? HttpContext.Current.User 似乎仍然返回一个 IPrinciple 所以这一切不应该有效吗?

非常感谢任何帮助。

【问题讨论】:

    标签: asp.net asp.net-identity iprincipal


    【解决方案1】:

    我发现这是用户未登录时造成的。我找到了两种解决方案:

    1. 当前用户未登录时不要尝试注入 (在这种情况下很简单,因为我刚刚从 我的登录控制器。
    2. 注入处理返回当前用户的工厂类。无论用户是否登录,Ninject 总是能够实例化和注入它。工厂类处理任何空异常等。

    我希望这对其他人有帮助。

    【讨论】:

      【解决方案2】:

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

      如果您希望在 User 对象上执行扩展方法以提取额外数据,则有几种不同的方法(使用声明是其中之一)。但是创建自己的CustomPrincipal 已成为过去,现在有更简单的方法可以做到这一点。

      【讨论】:

      • 真的,这很有趣。我将不得不做一些研究。感谢您的回复。
      • 这很有趣,我能否建议您指出其他一些方法可能是什么?
      最近更新 更多