IHttpContextAccessor在一个存储库中为空



—dotnet7—我正试图从httpcontextaccessor头中的令牌中获取我的用户id,我在Program.cs

中注册了我的存储库和httpcontextaccessor
builder.Services.AddScoped<IWardrobeService, WardobreService>();
builder.Services.AddScoped<IGuildService, GuildService>();
builder.Services.AddHttpContextAccessor();

衣橱服务,我可以使用访问器,它返回id。
WardrobeService.cs:

private readonly DataContext _context;
private readonly IMapper _mapper;
private readonly IEffectService _fxService;
private readonly IHttpContextAccessor _httpContext;
private readonly IDMService _dmService;
public WardobreService(DataContext context, IMapper mapper, IEffectService fxService, IHttpContextAccessor httpContext, IDMService dmService)
{   
_context = context;
_mapper = mapper;
_fxService = fxService;
_httpContext = httpContext;
_dmService = dmService;
}
// Needed Methods
private int GetCurrentUserId() => int.Parse(
_httpContext.HttpContext!.User.FindFirstValue(ClaimTypes.NameIdentifier)!
);

但是如果我在GuildService中尝试这个,访问器总是返回null。
GuildService.cs:

private readonly IMapper _mapper;
private readonly DataContext _context;
private readonly IHttpContextAccessor _httpContext;
private readonly IWardrobeService _wardrobe;
public GuildService(IMapper mapper, DataContext context, IHttpContextAccessor httpContext, IWardrobeService wardrobe)
{
_context = context;
_mapper = mapper;
_httpContext = httpContext;
_wardrobe = wardrobe;
}
// Needed Methods
private int GetCurrentUserId() => int.Parse(
_httpContext.HttpContext!.User.FindFirstValue(ClaimTypes.NameIdentifier)!
);
private async Task<Character> GetCurrentCharacter()
{
var c = await _context.Characters.FirstOrDefaultAsync(c => c.UserId == GetCurrentUserId());
return c!;
}

这里当我尝试使用GetCurrentCharacter(),我得到一个错误,因为GetCurrentUserId()返回null。据我所知,我在两个存储库中做了同样的事情,我不知道为什么_httpContext。HttpContext总是返回null.

我试着重写GuildService,但没有成功。我试着调用_wadrobeServiceGuildService;如果我这样做,那么问题发生在衣柜服务
Udpate:
通过在调用GuildService的控制器上添加[authorization]来解决问题。。这就是两个存储库之间的区别,一个是用[Authorize]在控制器上调用的,而另一个不是。

这里有很多#null的宽容。分解并检查。

private int GetCurrentUserId() 
{
var user = _httpContext.HttpContext?.User;
if(user == null) 
throw new ApplicationException("No user session");
var name = user.FindFirstValue(ClaimTypes.NameIdentifier);
if (string.IsNullOrEmpty(name))
throw new ApplicationException("No user name claim.");
var result = int.TryParse(name, out int userId)
if (!result)
throw new ApplicationException("User name claim not a User ID.");
return userId;
}

在用户会话状态不可检索的所有情况下,应该转储整个会话,强制用户重新身份验证。将其分解,看看实际设置(或未设置)的内容应该有助于缩小问题范围。

检查的区域应该是查看调用堆栈,以查看在整个请求中何时/何地调用了这个特定的存储库。如果它以某种方式被调用,而不在Http请求的范围内,那么上下文访问器可能无法解析当前会话。这个GuildService在哪里被注入/解析,它与其他工作的服务有什么不同?