我有一个具有自定义成员资格和角色提供者的 MVC 应用程序。我正在检查用户是否具有这样的角色:
public static bool CustomersVisible
{
get
{
return
HttpContext.Current.User != null &&
HttpContext.Current.User.Identity.IsAuthenticated &&
HttpContext.Current.User.IsInRole("Admin");
}
}
自定义角色提供程序如下所示:
public class DRRoleProvider : RoleProvider
{
private IUserProfileRepository _userProfileRepository;
private IRoleRepository _roleRepository;
public DRRoleProvider() {}
public DRRoleProvider(IUserProfileRepository userProfileRepository, IRoleRepository roleRepository)
{
_userProfileRepository = userProfileRepository;
_roleRepository = roleRepository;
}
. . .
public override bool IsUserInRole(string username, string roleName)
{
var user = _userProfileRepository.GetByUserName(username);
var role = _roleRepository.GetByName(roleName);
if (user != null)
{
return user.Roles != null && user.Roles.Contains(role);
}
return false;
}
编辑添加:这是我的 NinjectControllerFactory:
public class NinjectControllerFactory : DefaultControllerFactory
{
private IKernel ninjectKernel;
public NinjectControllerFactory()
{
ninjectKernel = new StandardKernel();
AddBindings();
}
protected override IController GetControllerInstance(RequestContext requestContext, Type controllerType)
{
return controllerType == null
? null
: (IController) ninjectKernel.Get(controllerType);
}
private void AddBindings()
{
ninjectKernel.Bind<ICustomerRepository>().To<CustomerRepository>();
ninjectKernel.Bind<IUserProfileRepository>().To<UserProfileRepository>();
ninjectKernel.Bind<IRoleRepository>().To<RoleRepository>();
ninjectKernel.Bind<ISessionFactory>().ToProvider<SessionFactoryBuilder>().InSingletonScope();
ninjectKernel.Bind<ISession>().ToMethod(CreateSession).InSingletonScope();
ninjectKernel.Inject(Membership.Provider);
ninjectKernel.Inject(Roles.Provider);
}
private ISession CreateSession(IContext context)
{
var session = context.Kernel.Get<ISessionFactory>().OpenSession();
return session;
}
}
当调用 IsUserInRole 方法时,我在 _userProfileRepository 上得到一个空引用异常。如何确保从 HttpContext.Current.User.IsInRole 调用存储库时被注入?从我自己的代码调用时它工作正常。