无法使用 webapi .net 8.0 中的配置管理器读取 appsettings.json 连接字符串

问题描述 投票:0回答:1

我正在使用 .net 8.0 框架开发 asp.net webapi,我有下面的代码 在我的 DBContext 中

当我直接输入连接字符串时,效果很好

    protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
    {
        optionsBuilder.UseSqlServer("server=.;database=myDb;trusted_connection=true;");
    }

这里我将连接字符串存储在 appsettings.json 文件中,但它不起作用。 我得到的只是对象而不是实例

    protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
    {
        base.OnConfiguring(optionsBuilder);
        optionsBuilder.UseSqlServer(ConfigurationManager.ConnectionStrings["Yoman"].ConnectionString);
    }

appsettings.json 文件看起来像这样

    {
      "Logging": {
        "LogLevel": {
          "Default": "Information",
          "Microsoft.AspNetCore": "Warning"
        }
      },
      "ConnectionStrings": {
        "Yoman": "server=xxxx;database=Tester;integrated security=true;multipleactiveresultsets=true;"
      }
    }

我能想到的唯一一件事是我的 DbContext 类驻留在 Data.Persisternce 项目中,但我添加了 该项目作为我进入 MainAPI 的参考点

你知道我可能做错了什么,为什么我无法使用 ConfigurationManager 读取连接字符串吗?

asp.net-core asp.net-web-api
1个回答
0
投票

您可以通过在program.cs文件中注入dbContext来简单地重写您的实现

var connectionString = builder.Configuration.GetConnectionString("Yoman");

builder.Services.AddDbContext<YourDbContext>(options =>
options.UseSqlServer(connectionString));

var app = builder.Build();

你可以像这样清理你的dbContext

public class YourDbContext : DbContext
{
    public YourDbContext(DbContextOptions<YourDbContext> options)
    : base(options)
    {
    }

// Your DbSet properties...
}
© www.soinside.com 2019 - 2024. All rights reserved.