Asp.Net Core 2.2通过当前用户更改数据库运行时
创始人
2024-09-14 17:01:21
0

要通过当前用户更改数据库运行时,可以使用Asp.Net Core 2.2提供的依赖注入功能和配置选项。

首先,在Startup.cs文件的ConfigureServices方法中注册数据库上下文:

services.AddDbContext(options =>
    options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));

接下来,在appsettings.json文件中配置数据库连接字符串:

"ConnectionStrings": {
  "DefaultConnection": "Data Source=(localdb)\\MSSQLLocalDB;Initial Catalog=YourDatabase;Integrated Security=True;Connect Timeout=30;Encrypt=False;TrustServerCertificate=False;ApplicationIntent=ReadWrite;MultiSubnetFailover=False"
}

然后,创建一个类来表示当前用户,例如:

public class CurrentUser
{
    public string UserId { get; set; }
    // 其他用户属性
}

接下来,在Startup.cs文件的ConfigureServices方法中注册CurrentUser类:

services.AddScoped(serviceProvider =>
{
    var httpContextAccessor = serviceProvider.GetRequiredService();
    var userId = httpContextAccessor.HttpContext.User.FindFirst(ClaimTypes.NameIdentifier)?.Value;
    // 如果需要其他用户属性,可以在这里获取并设置
    return new CurrentUser { UserId = userId };
});

然后,在ApplicationDbContext类中使用CurrentUser类,例如:

public class ApplicationDbContext : DbContext
{
    private readonly CurrentUser _currentUser;

    public ApplicationDbContext(DbContextOptions options, CurrentUser currentUser)
        : base(options)
    {
        _currentUser = currentUser;
    }

    public DbSet YourEntities { get; set; }

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

        // 设置当前用户作为默认值
        modelBuilder.Entity()
            .Property(e => e.CreatedBy)
            .HasDefaultValueSql($"'{_currentUser.UserId}'");
    }
}

最后,在使用数据库上下文的地方,可以通过依赖注入获取当前用户的实例,例如:

public class YourService
{
    private readonly ApplicationDbContext _dbContext;
    private readonly CurrentUser _currentUser;

    public YourService(ApplicationDbContext dbContext, CurrentUser currentUser)
    {
        _dbContext = dbContext;
        _currentUser = currentUser;
    }

    public void DoSomething()
    {
        // 使用当前用户ID进行操作
        var entity = new YourEntity { CreatedBy = _currentUser.UserId };
        _dbContext.YourEntities.Add(entity);
        _dbContext.SaveChanges();
    }
}

通过以上步骤,您可以在Asp.Net Core 2.2中通过当前用户更改数据库运行时。请根据您的实际需求修改代码示例。

相关内容

热门资讯

重大推荐!gg扑克辅助,雀神广... 重大推荐!gg扑克辅助,雀神广东麻雀小程序怎么赢,麻友圈2辅助器怎么安装(有挂规律)1)麻友圈2辅助...
发现一款!wopoker系统机... 发现一款!wopoker系统机制,微信雀神小程序可以作假吗,麻辣竞技外 挂真的假的(有挂介绍)进入游...
今日焦点!微扑克有辅助插件,雀... 今日焦点!微扑克有辅助插件,雀神小程序辅助app,喜扣跑胡子免费辅助器(有挂规律);1、喜扣跑胡子免...
玩家必看科普!gg扑克发牌问题... 玩家必看科普!gg扑克发牌问题,微信雀神广东麻将提高胜率技巧,约战武汉麻将有挂吗(有挂辅助)1、玩家...
一起来探讨!扑克时间假假,微信... 一起来探讨!扑克时间假假,微信雀神麻将软挂神器,小闲有没有外挂(有挂细节)1)小闲有没有外挂辅助挂:...
推荐攻略!德扑软件开发,雀神广... 推荐攻略!德扑软件开发,雀神广东麻将系统调好,丽水茶苑双扣辅助工具(有挂揭秘)1)丽水茶苑双扣辅助工...
重大科普!aapoker透明挂... 重大科普!aapoker透明挂多久被封,广东雀神麻雀胜率,佛手十三道有没有辅助器(有挂揭秘);佛手十...
今日公布!微扑克辅助测试,广东... 今日公布!微扑克辅助测试,广东雀神辅助器在哪下载,长城情怀麻将有挂吗(有挂脚本)1、该软件可以轻松地...
玩家必看分享!微扑克德州专用辅... 玩家必看分享!微扑克德州专用辅助器,微信雀神小程序可以开挂吗,旺旺麻将有挂么(有挂方法);1、下载好...
重大推荐!aapoker有挂,... 您好,心悦麻将有没有挂这款游戏可以开挂的,确实是有挂的,需要了解加微【757446909】很多玩家在...