1

由于我在 VS2012 中将我的项目升级到 MVC5,因此我实现的自定义主体不再起作用。

校长:

public class CustomPrincipal : IPrincipal
{
    public Boolean IsInRole(String role)
    {
        return ((CustomIdentity)Identity).User.Roles.Any(r => r.Name == role);
    }

    public IIdentity Identity { get; private set; }

    public CustomPrincipal(UserSession userSession)
    {
        Identity = new CustomIdentity(userSession);
    }
}

自定义身份:

public class CustomIdentity : IIdentity
{
    public String Name { get; private set; }

    public String AuthenticationType
    {
        get
        {
            return "CustomAuthentication";
        }
    }

    public Boolean IsAuthenticated { get; private set; }

    public User User { get; private set; }
    public UserSession UserSession { get; private set; }

    public CustomIdentity(UserSession userSession)
    {
        User = userSession.User;
        UserSession = userSession;
        Name = userSession.User.UserName;
        IsAuthenticated = userSession.User.IsApproved && !userSession.User.IsDisabled && !userSession.User.IsLockedOut;
    }
}

我如何设置用户:

var principal = new CustomPrincipal(userSession);
HttpContext.Current.User = principal;

[Authorize(Roles = "Administrator")]属性不再起作用,也不再起作用var a = HttpContext.User.IsInRole("Administrator");

当我在它处放置断点时,IsInRole它永远不会到达那里,但是构造的被调用并且HttpContext.Current.User确实包含该CustomPrincipal对象。

有什么可以改变或错误的?

4

0 回答 0