gpt4 book ai didi

c# - ASP.NET Core 2.2 在 DbContext 中获取 userId

转载 作者:行者123 更新时间:2023-12-05 05:09:23 26 4
gpt4 key购买 nike

我是 ASP.NET Core 的新手。我想使用 Entity Framework Core 和 ASP.NET Identity 创建 ASP.NET Core 2.2 WebAPI。此外,我想使用 JWT 通过 token 来保护对该 WebAPI 的访问。

我已成功将用户插入数据库并从我的 API 取回 token ,并且 token 身份验证正在运行。

但是,我还想软删除数据库记录并跟踪谁删除/更新/添加了记录。测试表是 Countries,其中字段只有 TitleDescription

到目前为止,我已经颠倒了互联网,但没有帮助:(

Las 我试过的是(userId 是 null):

  • 在 startup.cs 中:

    services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();
  • 在我的 AppDbContext.cs 中

    public class AppDbContext : IdentityDbContext<AppUser>{

    public AppDbContext(DbContextOptions options) : base(options)
    {
    }

    public DbSet<AppUser> AppUsers { get; set; }

    public DbSet<Country> Countries { get; set; } // just for testing

    protected override void OnModelCreating(ModelBuilder builder)
    {
    base.OnModelCreating(builder);

    // TODO - IGNORE THIS
    //builder.Entity<AppUser>().Property<bool>("IsDeleted");
    //builder.Entity<AppUser>().HasQueryFilter(m => EF.Property<bool>(m, "IsDeleted") == false);
    }

    public override async Task<int> SaveChangesAsync(CancellationToken cancellationToken = default(CancellationToken))
    {
    CheckBeforeSaving();
    return (await base.SaveChangesAsync(true, cancellationToken).ConfigureAwait(false));
    }

    private void CheckBeforeSaving()
    {
    var httpContextAccessor = this.GetService<IHttpContextAccessor>();
    var userId = httpContextAccessor?.HttpContext.User.FindFirstValue(ClaimTypes.NameIdentifier);

    foreach (var entry in ChangeTracker.Entries())
    {
    switch (entry.State)
    {
    case EntityState.Detached:
    break;
    case EntityState.Unchanged:
    break;
    case EntityState.Deleted:
    entry.State = EntityState.Modified;
    entry.CurrentValues["IsDeleted"] = true;
    entry.CurrentValues["DeletedBy"] = userId;
    entry.CurrentValues["Deleted"] = DateTime.Now;
    break;
    case EntityState.Modified:
    entry.CurrentValues["UpdatedBy"] = userId;
    entry.CurrentValues["Updated"] = DateTime.Now;
    break;
    case EntityState.Added:
    entry.CurrentValues["IsDeleted"] = false;
    entry.CurrentValues["CreatedBy"] = userId;
    entry.CurrentValues["Created"] = DateTime.Now;
    entry.CurrentValues["Description"] = userId;
    break;
    default:
    break;
    }
    }
    }}}

最佳答案

尝试将 IHttpContextAccessor 直接注入(inject)到 ApplicationDbContext 中:

public class ApplicationDbContext : IdentityDbContext<AppUser>
{
private readonly IHttpContextAccessor _httpContextAccessor;
public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options, IHttpContextAccessor httpContextAccessor)
: base(options)
{
_httpContextAccessor= httpContextAccessor;
}

//other methods

private void CheckBeforeSaving()
{
var userId = _httpContextAccessor?.HttpContext.User.FindFirstValue(ClaimTypes.NameIdentifier);
//...
}
}

关于c# - ASP.NET Core 2.2 在 DbContext 中获取 userId,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57604410/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com