我有一个授权处理程序,我正在注入一个自定义personService。我通过默认DI连接了处理程序和personService。人员服务IhttpContextAccessor在我的应用程序的其他地方工作正常,但是当从授权处理程序调用它时,httpcontext始终为null。
以下是AuthHandler:
public class NoChildrenRequirement : AuthorizationHandler<NoChildrenRequirement>, IAuthorizationRequirement
{
private readonly IPersonService _personService;
public NoChildrenRequirement(IPersonService personService)
{
_personService = personService;
}
protected override void Handle(AuthorizationContext context, NoChildrenRequirement requirement)
{
var user = context.User;
var identity = user.Identity;
var isAuthenticated = identity.IsAuthenticated;
var currentPerson = _personService.CurrentPerson();
if (isAuthenticated && currentPerson != null && !currentPerson.IsAChild)
{
context.Succeed(requirement);
return;
}
context.Fail();
}
}
这是我在启动时连接的地方:
services.AddTransient<NoChildrenRequirement>();
services.Configure<AuthorizationOptions>(options =>
{
options.AddPolicy("NoChildren", policy => policy.Requirements.Add(
services.BuildServiceProvider().GetRequiredService<NoChildrenRequirement>()));
});
这是人事服务的开始:
public class PersonService : IPersonService
{
private readonly IPersonRepository _repository;
private readonly IMemoryCache _memoryCache;
private readonly IConfigService _configService;
private readonly IHttpContextAccessor _context;
private readonly IResourceService _resourceService;
private readonly string _cacheKey = "Person_";
public PersonService(IPersonRepository repository, IMemoryCache memoryCache,
IConfigService configService, IHttpContextAccessor context,
IResourceService resourceService)
{
_repository = repository;
_memoryCache = memoryCache;
_configService = configService;
_context = context;
_resourceService = resourceService;
}
这是我在启动时连接个人服务的地方:
services.AddTransient<IPersonService, PersonService>();
如果我访问:IHttpContextAccessor _context;当我从authhandler调用personservice时,所有其他依赖关系正确连接,甚至具体的HttpContextAccessor值不为null,但HttpContextAccessor中的HttpContext为null。有任何想法吗?