ASP.NET Core 2.2在DbContext中获取userId

我对 ASP.NET Core 很陌生。我想使用 Entity Framework Core 和 ASP.NET Identity 创建 ASP.NET Core 2.2 WebAPI。另外,我想使用 JWT 来通过令牌保护对该 WebAPI 的访问。


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


但是,我还想软删除数据库记录并跟踪谁删除/更新/添加了记录。其测试表是“国家”,其中字段只有Title和Description。


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


我尝试过的最后一件事是(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;

            }

        }

    }}}


开满天机
浏览 106回答 3
3回答

狐的传说

尝试直接IHttpContextAccessor 注入ApplicationDbContext:public class ApplicationDbContext : IdentityDbContext<AppUser>{&nbsp; &nbsp; private readonly IHttpContextAccessor _httpContextAccessor;&nbsp; &nbsp; public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options, IHttpContextAccessor httpContextAccessor)&nbsp; &nbsp; &nbsp; &nbsp; : base(options)&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; _httpContextAccessor= httpContextAccessor;&nbsp; &nbsp; }&nbsp; &nbsp; //other methods&nbsp; &nbsp;private void CheckBeforeSaving()&nbsp; &nbsp;{&nbsp; &nbsp; &nbsp; &nbsp;&nbsp;&nbsp; &nbsp; &nbsp;var userId = _httpContextAccessor?.HttpContext.User.FindFirstValue(ClaimTypes.NameIdentifier);&nbsp; &nbsp; &nbsp;//...&nbsp; &nbsp;}}

神不在的星期二

这是我在 .net core 2.2 中获取用户 ID 的方法首先,您需要在 Startup.cs 中注册services.AddSingleton<IActionContextAccessor, ActionContextAccessor>();然后为您服务private readonly IHttpContextAccessor _httpContextAccessor;public UserService(&nbsp; &nbsp; IHttpContextAccessor httpContextAccessor){}var currentUserGuid = _httpContextAccessor?.HttpContext?.User?.FindFirst(UserClaimsKey.Sub)?.Value;

白板的微信

private async Task<ApplicationUser> GetUserDetailsAnsyc(){&nbsp; return await userManager.GetUserAnsync(HttpContext.User);}var user = await GetUserDetailsAnsyc();Console.WriteLine(user.Id.ToString());
打开App,查看更多内容
随时随地看视频慕课网APP