MVC5自定义主体不是IsInRole不工作

时间:2013-10-27 18:09:44

标签: asp.net-mvc

自从我在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对象。

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

0 个答案:

没有答案