Azure API 不使用配置中的连接字符串,而是使用本地连接字符串

Azure API doesnt use connection string from configuration, but local one

我在 azure api 配置中有同名的连接字符串,但是当我转到 api 时,招摇,它告诉我 - System.PlatformNotSupportedException: LocalDB is not supported on this platform. 返回 500 状态。 这就是我从 api:

获取连接字符串的方式
private string _connectionString = string.Empty;

        public string GetConnectionString(string name)
        {
            var configurationBuilder = new ConfigurationBuilder();
            var path = Path.Combine(Directory.GetCurrentDirectory(), "appsettings.json");
            configurationBuilder.AddJsonFile(path, false);

            var root = configurationBuilder.Build();
            _connectionString = root.GetSection("ConnectionStrings").GetSection(name).Value;
            var appSetting = root.GetSection("ApplicationSettings");

            return _connectionString;
        }

API 项目在 .net 5

这是因为您仅从文件构建配置,而您需要添加 AddEnvironmentVariables 以便它从 Azure 应用服务配置添加属性

试试这个:

  public string GetConnectionString(string name)
        {
            var path = Path.Combine(Directory.GetCurrentDirectory(), "appsettings.json");
            var root = new ConfigurationBuilder()
                .AddJsonFile(path, false)
                .AddEnvironmentVariables()
                .Build();

            _connectionString = root.GetSection("ConnectionStrings").GetSection(name).Value;
            var appSetting = root.GetSection("ApplicationSettings");

            return _connectionString;
        }

由于它在库中,您需要添加包含 AddEnvironmentVariables 扩展名的包 Microsoft.Extensions.Configuration.EnvironmentVariables

另一种方法是在您的项目中添加 FrameworkReference,但这会带来很多您可能不需要的 asp.net 核心内容

  <ItemGroup>
    <FrameworkReference Include="Microsoft.AspNetCore.App" />
  </ItemGroup>