【问题标题】:Getting Database ConnectionString from appsettings.{Environement}.json in .Net Core 7 inside Program.cs?从 Program.cs 中的 .Net Core 7 中的 appsettings.{Environment}.json 获取数据库连接字符串?
【发布时间】:2022-11-16 21:07:53
【问题描述】:

在旧版本的 ASP.Net Core 中,你有 startup.cs 文件,你可以在其中做很多工作,包括读取和设置应​​用程序环境,然后基于它你可以读取不同版本的 appsettings.json 文件。在新的 ASP.Net Core 7 中,他们摆脱了 Startup.cs 并大大简化了 program.cs 文件。现在我不知道如何读取环境,然后将 Entity Framework 7 传递给我的连接字符串。环顾四周,我发现不适用于版本 7 的所有答案或告诉您通过重新制作整个 Startup.cs 文件来撤消版本 7 中的所有工作。我们应该如何根据 .Net 7 中的环境注入连接字符串?

我确实有代码可以从基本的 appsettings.json 文件中读取并且可以正常工作,还有一个部分可以读取环境,但是它是在 DbContext 注入之后进行设置的。这是我的 program.cs 文件,我只是迷失了需要更新的内容。我查看了 Microsoft 文档,但没有看到任何适用于环境和字符串注入的内容。

var builder = WebApplication.CreateBuilder(args);

//Add Services (builder.Services.AddScoped<IService, Service>();
builder.Services.AddScoped<INavigationHelper, NavigationHelper>();
builder.Services.AddAuthentication(OpenIdConnectDefaults.AuthenticationScheme).AddMicrosoftIdentityWebApp(builder.Configuration.GetSection("AzureAd"));

builder.Services.AddAuthorization(options =>
{
    options.FallbackPolicy = options.DefaultPolicy;
});

builder.Services.AddControllersWithViews(options =>
{
    var policy = new AuthorizationPolicyBuilder().RequireAuthenticatedUser().Build();
    options.Filters.Add(new AuthorizeFilter(policy));
});

builder.Services.AddRazorPages().AddMicrosoftIdentityUI();
builder.Services.AddDbContext<SiteDbContext>(options => options.UseSqlServer(builder.Configuration.GetConnectionString("Database")));
var app = builder.Build();

if (!app.Environment.IsDevelopment()) { app.UseHsts(); }

app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();
app.UseAuthentication();
app.UseAuthorization();
app.MapRazorPages();
app.MapControllers();
app.Run();

应用设置.json:

{
  "AzureAd":
  {
    "Instance": "https://login.microsoftonline.com/",
    "Domain": "",
    "TenantId": "",
    "ClientId": "",
    "CallbackPath": "",
    "ClientSecret": "Client secret from app-registration. Check user secrets/azure portal.",
    "ClientCertificates":
    [
    ]
  },
  "Logging":
  {
    "LogLevel":
    {
      "Default": "Information",
      "Microsoft.AspNetCore": "Warning"
    }
  },
  "AllowedHosts": "*",

  "ConnectionStrings":
  {
    "Database": ""
  }
}

appsettings.development.json

{
  "Logging":
  {
    "LogLevel":
    {
      "Default": "Information",
      "Microsoft.AspNetCore": "Warning"
    },

    "ConnectionStrings":
    {
      "Database": ""
    }
  }
}

【问题讨论】:

    标签: c# asp.net-core entity-framework-core asp.net-core-7.0 ef-core-7.0


    【解决方案1】:

    我们可以从如下环境中读取配置。在读取值时,最新添加的文件中的键将获得优先权。

    例如,如果“默认”连接字符串同时出现在 appsettings.json 和 appsettings.Development.json 中,则后一个文件中的值将是结果值。

    using Microsoft.Extensions.Configuration;
    
    var builder = WebApplication.CreateBuilder(args);
    
    // Add services to the container.
    
     var config = new ConfigurationBuilder()
                .AddJsonFile("appsettings.json")
                .AddJsonFile($"appsettings.{builder.Environment.EnvironmentName}.json", optional: true)
                .Build();
    
    var defaultConnectionString = config.GetConnectionString("Default");
    
    
    Console.WriteLine($"Default ConnectionString: {defaultConnectionString}");
    
    

    【讨论】:

    • 您的代码如何知道我在哪个环境中运行并从正确的 JSON 文件中提取?假设我有一个 development,json 和一个 production.json 文件,我需要为正确的环境读取正确的文件。此外,我 99% 确定您提供的用于添加文件的代码是由 EF 7 自动完成的。
    • 你可以像下面那样做, var config = new ConfigurationBuilder() .AddJsonFile("appsettings.json") .AddJsonFile($"appsettings.{builder.Environment.EnvironmentName}.json", optional: true) .Build();
    • 已更新代码以反映@MatthewVerstraete
    • 阅读 learn.microsoft.com/en-us/aspnet/core/fundamentals/… 在我看来,EF 已经做了你想让我做的事情。所以问题仍然是它没有从正确的 appsetting.{Environment}.json 文件中读取它出现
    • 是的。感谢您指出。我同意 Neil 关于 ConnectionString 设置值不在开发配置中的正确层次结构中的评论
    【解决方案2】:
    builder.Configuration.GetConnectionString("Database")
    

    将根据所选环境使用适当的 appsettings.json 文件。如果您查看项目中的 Properties 文件夹并检查 launchsettings.json 文件,您应该会看到如下内容:

    {
        "iisSettings": {
          "windowsAuthentication": false,
          "anonymousAuthentication": true,
          "iisExpress": {
            "applicationUrl": "http://localhost:30787",
            "sslPort": 44345
          }
        },
        "profiles": {
          "Cosmos.Application.Server": {
            "commandName": "Project",
            "dotnetRunMessages": true,
            "launchBrowser": false,
            "inspectUri": "{wsProtocol}://{url.hostname}:{url.port}/_framework/debug/ws-proxy?browser={browserInspectUri}",
            "applicationUrl": "https://localhost:7138;http://localhost:5138",
            "environmentVariables": {
              "ASPNETCORE_ENVIRONMENT": "Development"
            }
          },
          "IIS Express": {
            "commandName": "IISExpress",
            "launchBrowser": true,
            "inspectUri": "{wsProtocol}://{url.hostname}:{url.port}/_framework/debug/ws-proxy?browser={browserInspectUri}",
            "environmentVariables": {
              "ASPNETCORE_ENVIRONMENT": "Development"
            }
          }
        }
      }
    

    在上面,这意味着 ASPNETCORE_ENVIRONMENT 设置为 Development,这将确定在调用时在 program.cs 中使用哪个 appsettings 文件:

    builder.Configuration ...
    

    【讨论】:

    • 所以确实有"ASPNETCORE_ENVIRONMENT": "Development"。但是,如果我将我的连接字符串放在 appsettings.Development.json 中,它不会被读取,但如果我将它复制/粘贴到 appsettings.json 中,它就可以正常读取。
    • 您确定您的开发文件中没有拼写错误吗?如果在特定于环境的文件中找不到请求的值,它将恢复为值的基本 appsettings.json 文件。您可以发布您的 appsettings.Development.json 文件(隐藏敏感数据)吗?
    • 我没有看到,但会使用两个 json 文件中的代码更新帖子以供审核。
    • 您的“ConnectionStrings”嵌套在日志记录中。它必须是根部分。
    • 好吧,我非常讨厌自己。我花了几个小时试图解决这个问题,但从未注意到我搞砸了。谢谢你看到它。
    猜你喜欢
    • 2021-01-09
    • 2021-05-29
    • 1970-01-01
    • 1970-01-01
    • 2020-07-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-01-27
    相关资源
    最近更新 更多