这应该很简单,但是在我查阅了所有资料之后,我还是没弄明白。这是我的需求:我有一张自定义的用户表(目前没有角色),我想对其进行授权。为此,我需要实现一个自定义的Membership提供程序,我已经完成了这个步骤。但我的问题是,如何设置一个自定义的IPrincipal到HttpContext.Current.User中?这应该在哪里发生?假设我的设置如下所示:
public class CustomMembershipProvider : MembershipProvider
{
private IUserRepository _repository;
public CustomMembershipProvider(IUserRepository repository)
{
_repository = repository;
}
public override bool ValidateUser(string username, string password)
{
//check user repository
}
//additional methods omitted for brevity
}
我有一个自定义用户类,实现了IPrincipal
和IIdentity
接口。
public class CustomUser : IPrincipal
{
public CustomUser(string name, int userId, string additionalInfo)
{
Identity = new CustomIdentity(name, userId, additionalInfo);
}
public IIdentity Identity { get; private set; }
public bool IsInRole(string role)
{
return true;
}
}
public class CustomIdentity : IIdentity
{
public CustomIdentity(string name, int userId, string additionalInfo)
{
Name = name;
UserId = userId;
AdditionalInfo = additionalInfo;
}
public string Name { get; private set; }
public string AuthenticationType
{
get { return "CustomAuth"; }
}
public bool IsAuthenticated
{
get { return !String.IsNullOrEmpty(Name); }
}
public int UserId { get; private set; }
public string AdditionalInfo { get; private set; }
}
所以我的问题是,将Context.User设置为此自定义用户实例的正确位置在哪里?我需要一个自定义授权属性吗?如果需要,那么它应该是什么样子?