自从我在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
对象。
有什么可以改变或错误的?