【问题标题】:Running a published version of an asp.net core from the cli从 cli 运行已发​​布版本的 asp.net 核心
【发布时间】:2020-02-10 23:40:45
【问题描述】:

从 cli 运行 asp.net 核心应用的发布配置版本时遇到问题。

应用程序非常简单,我使用 Api 模板创建了一个新的 Asp.Net,因此我得到了天气预报应用程序。

我使用 Entity Framework 核心添加了一个 SqlServer 项目,我正在使用从 appsettings.Production.json 文件中获取的 connectionString 对其进行配置

  "ConnectionString": {
    "SqlServer": "Server = .; Database = test_Prod; Trusted_Connection = True; "
  },

我的 Startup 类构造函数

    public Startup(IWebHostEnvironment environment)
    {
        _configurationRoot = new ConfigurationBuilder()
            .SetBasePath(environment.ContentRootPath)
            .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
            .AddJsonFile($"appsettings.{ environment.EnvironmentName }.json", optional: true, reloadOnChange: true)
            .AddEnvironmentVariables()
            .Build();

        _environment = environment;
    }

以及配置方法

    public void Configure(IApplicationBuilder app, ILogger<Startup> logger)
    {
        if (_environment.IsProduction())

            logger.LogInformation($" { Environment.NewLine } Environment { _environment.EnvironmentName } launched { Environment.NewLine }");

            logger.LogInformation($" ConnectionString : { _configurationRoot.GetSection("ConnectionString").GetValue<string>("SqlServer") }");            { 

            AppContext dbContext = app.ApplicationServices.GetRequiredService<AppContext>();
        }

我收到以下异常

crit: Microsoft.AspNetCore.Hosting.Diagnostics[6]
      Application startup exception
System.ArgumentNullException: Value cannot be null. (Parameter 'connectionString')
   at Microsoft.EntityFrameworkCore.Utilities.Check.NotEmpty(String value, String parameterName)
   at Microsoft.EntityFrameworkCore.SqlServerDbContextOptionsExtensions.UseSqlServer(DbContextOptionsBuilder optionsBuil

检查我的日志我得到 Environment is Production 并且 ConnectionString 是空的

以下是我正在执行的命令

  1. dotnet publish -c Release -o out

  2. dotnet .\out\myApp.dll

我做错了什么?

如果从 Visual Studio 运行,并且如果使用运行命令从 dotnet cli 运行,应用程序也可以运行

dotnet run -p .\myApp\myApp.csproj

【问题讨论】:

  • 您将 appsettings.Production.json 的属性设置为“始终复制”(所以它在启动应用程序时包含在构建中)?
  • 是的,我已经在所有 appsettings.Property.json 文件上设置了 Copy Always 属性,并且我也刚刚尝试使用 GetConnectionString 方法。同样的例外,

标签: c# asp.net-core .net-core dotnet-cli


【解决方案1】:
  1. 您需要确保 appsettings.json 或 appsettings.production.json 实际存在于您发布的文件夹中
  2. 如果您的连接字符串在 appsettings.production.json 中,您需要转到系统环境变量(开始 > 运行 > rundll32.exe sysdm.cpl,EditEnvironmentVariables)并手动将 ASPNETCORE_ENVIRONMENT 变量设置为 PRODUCTION。请记住,Visual Studio 在运行您的应用时会暂时添加该环境变量。
  3. 第 2 步的替代方法是将连接字符串移动到 appsettings.json

【讨论】:

  • 设置环境变量后,您需要重新启动命令提示符以获取新变量。
猜你喜欢
  • 2020-04-23
  • 1970-01-01
  • 2017-07-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-04-29
  • 2011-09-23
  • 1970-01-01
相关资源
最近更新 更多