当前,我可以通过将其传递到控制器,服务层,工作单元,实体框架来访问API中的Auth0令牌。
我想通过仅使用依赖注入将其抽象化并将令牌传递给实体框架。有人对如何执行此操作有任何提示吗?
public class HomeController : ControllerBase
{
private readonly IService _service;
public HomeController( IService service)
{
_service = service;
}
[HttpDelete("{id}")]
public async Task<ActionResult> Delete(int id)
{
string accessToken = User.Claims.FirstOrDefault(c => c.Type == ClaimTypes.NameIdentifier).Value;
_service.SetToken(accessToken);
await _service.Delete(id);
return Ok();
}
我继续执行此过程,将令牌通过每一层的SetToken方法向下传递。我正在寻找一种避免这种情况的方法,以使我的代码更具可维护性,因为我将要使用具有多个方法的多个控制器,并且将每个方法和控制器都传递给它很麻烦。谢谢
答案 0 :(得分:0)
要访问User
中的DbContext
,可以尝试如下解决服务:
public class ApplicationDbContext : IdentityDbContext
{
private readonly IHttpContextAccessor _httpContextAccessor;
public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options
, IHttpContextAccessor httpContextAccessor)
: base(options)
{
_httpContextAccessor = httpContextAccessor;
}
public override Task<int> SaveChangesAsync(bool acceptAllChangesOnSuccess, CancellationToken cancellationToken = default)
{
var httpContext = _httpContextAccessor.HttpContext;
string accessToken = httpContext.User.Claims.FirstOrDefault(c => c.Type == ClaimTypes.NameIdentifier).Value;
return base.SaveChangesAsync(acceptAllChangesOnSuccess, cancellationToken);
}
}