在 RevokeAuthenticationEvents.cs 中处理 CatalogContext 的数据时,将会销毁在 CatalogContext 的构造函数中注入的 IHttpContextAccessor

作者: Cheunglik创建于 2023年9月9日更新于 2023年9月9日

如果我在 CatalogContext 的构造函数中只注入 IHttpContextAccessor,它就能正常工作了! public CatalogContext(DbContextOptions options, IHttpContextAccessor httpContextAccessor) : base(options) { var name = httpContextAccessor.HttpContext?.User.Claims.SingleOrDefault(x => x.Type == ClaimTypes.NameIdentifier)?.Value ?? ""; } 如果用户已登录,我可以在上下文的构造函数中获取用户的 ID。https://GitHub.com/Cheunglik/eShopOnWeb/commit/5ca53d7675bc98baf0ff9c5e1d27c16e16f922ea withUserClaims 但是,我在 RevokeAuthenticationEvents 中添加了一些数据处理,如 ICatalogItemViewModelService。 public RevokeAuthenticationEvents(IMemoryCache cache, ILogger logger, ICatalogItemViewModelService catalogItemViewModelService) { _cache = cache; _logger = logger; _catalogItemViewModelService = catalogItemViewModelService; } https://GitHub.com/Cheunglik/eShopOnWeb/commit/5ca53d7675bc98baf0ff9c5e1d27c16e16f922ea 即使用户已登录,我也无法在上下文的构造函数中获取用户的 ID。 withoutUserClaims 我只是从原始主分支 https://GitHub.com/dotnet-architecture/eShopOnWeb 中分支,并添加了两个简单的注释。它非常容易重现。实际上,我想在 Cookie 的 CookieAuthenticationEvents 中处理一些数据,我将在 user.claims 中添加一些租户记录。 当用户请求控制器 => 服务 => 库 => dbContext 时。dbContext 可以使用 modelBuilder.Entity.HasQueryFilter(从 userclaim 的属性)来隔离不同的租户记录。

内容来源: dotnet-architecture/eShopOnWeb