【问题标题】:EFCore "Value cannot be null. (Parameter 'connectionString')" if value is in environment variablesEFCore“值不能为空。(参数'connectionString')”如果值在环境变量中
【发布时间】:2021-06-02 15:26:07
【问题描述】:

在带有 EFCore-5 的 Asp.NET Core Web 应用程序中,我有以下 ConfigureServices

// ...
services.AddRouting(options => options.LowercaseUrls = true);

// get the connection string from secrets/env.variables
string connectionString = Configuration.GetConnectionString("MyWebApp"); /// <<< HERE
services.AddDbContext(connectionString);

services.AddDatabaseDeveloperPageExceptionFilter();    
services.AddControllersWithViews();
// ...

还有AddDbContext扩展方法:

public static void AddDbContext(this IServiceCollection services, string connectionString) =>
        services.AddDbContext<ApplicationDbContext>(options =>
        {
            options.UseSqlServer(connectionString,    /// <<< HERE
                providerOptions =>
                {
                    providerOptions
                        .EnableRetryOnFailure(
                            maxRetryCount: 5, 
                            maxRetryDelay: TimeSpan.FromSeconds(30),
                            errorNumbersToAdd: null)
                        .UseQuerySplittingBehavior(QuerySplittingBehavior.SplitQuery);
                });
            options.EnableSensitiveDataLogging();

如果我将连接字符串放在appsettings.Production.json 中,站点运行良好,但是一旦我将其删除并放入 EnvironmentVariables,页面就会出现 500 错误,并且在我的日志中:

System.ArgumentNullException:值不能为空。 (范围 'connectionString')在 Microsoft.EntityFrameworkCore.Utilities.Check.NotEmpty(字符串值, 字符串参数名称)在 Microsoft.EntityFrameworkCore.SqlServerDbContextOptionsExtensions.UseSqlServer(DbContextOptionsBuilder optionsBuilder,字符串连接字符串,操作`1 sqlServerOptionsAction)

错误指向上面代码中用第二个HERE标记的行。

我这样设置环境变量:

【问题讨论】:

  • 在创建主机构建器时,您在Program.cs 中做了什么不同的事情吗?您是否尝试过在创建 env var 后关闭 VS 并重新打开?环境可能只加载一次并缓存。
  • @DavidG,这与 Visual Studio 无关,而是在生产中。在生产环境中,我们通常没有作为 Web 服务器的 Visual Studio

标签: asp.net-core environment-variables connection-string .net-5 ef-core-5.0


【解决方案1】:

默认配置加载以DOTNET_ASPNETCORE_为前缀的环境变量和命令行参数。

基于此,你应该使用

ASPNETCORE_ConnectionStrings__MyWebAppASPNETCORE_ConnectionStrings:MyWebApp

可以用AddEnvironmentVariables配置自定义前缀:

public class Program
{
    public static void Main(string[] args)
    {
        CreateHostBuilder(args).Build().Run();
    }

    public static IHostBuilder CreateHostBuilder(string[] args) =>
        Host.CreateDefaultBuilder(args)
            .ConfigureAppConfiguration((hostingContext, config) =>
            {
                config.AddEnvironmentVariables(prefix: "MyCustomPrefix_");
            })
            .ConfigureWebHostDefaults(webBuilder =>
            {
                webBuilder.UseStartup<Startup>();
            });
}

【讨论】:

    【解决方案2】:

    最后我设法让它工作了。我的解决方案是使用SQLCONNSTR_MyWebApp(作为System,而不是User 变量)并且应用程序的环境变量发生任何变化之后, 考虑到它在命令提示符下执行net stop was /y 后跟net start w3svc (docs)

    从 IIS 管理器重新启动 IIS不会重新加载正确环境变量中的更改...

    【讨论】:

    • 您可以按照我解释here的步骤3和4进行操作
    猜你喜欢
    • 1970-01-01
    • 2021-10-11
    • 1970-01-01
    • 1970-01-01
    • 2017-04-13
    • 1970-01-01
    • 1970-01-01
    • 2017-08-07
    • 1970-01-01
    相关资源
    最近更新 更多