无法读取 .NET Core API 项目中的应用程序设置

Can't read app settings in .NET Core API project

我有一个 .NET Core API 项目,我正在尝试从 appsettings.json 文件中读取一些设置。

文件如下所示:

{
  "Logging": {
    "IncludeScopes": false,
    "Debug": {
      "LogLevel": {
        "Default": "Warning"
      }
    },
    "Console": {
      "LogLevel": {
        "Default": "Warning"
      }
    }
  },
  "ConnectionString": "abc"
}

我正在尝试阅读 ConnectionString 设置,如下所示:

ConfigurationManager.AppSettings["ConnectionString"];

但我得到 null,显然根本没有检测到任何应用设置。

编辑:

这是我现在拥有的:

startup.cs

public class Startup
    {
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }

        public static IConfiguration Configuration { get; set; }

        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddDbContext<MyContext>();
            services.AddMvc();
            services.Configure<ConnectionStringSettings>(Configuration);
        }
}

ConnectionStringSettings.cs

 public class ConnectionStringSettings
    {
        public string ConnectionString { get; set; }
    }

appsettings.json

{
  "Logging": {
    ...
  },
  "ConnectionStrings": {
    "Debug": "abc"
  }
}

MyContext.cs public class MyContext : DbContext { 字符串 x;

    public MyContext() { }

    public MyContext(DbContextOptions<MyContext> options)
        : base(options) { }

    public MyContext(IOptions<ConnectionStringSettings> connectionStringSettings)
    {
        x = connectionStringSettings.Value.ConnectionString;
    }

    protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
    {
       //here I need my connection string
        optionsBuilder.UseMySql(connectionString);
    }

}

对于 .NET Core 2.x 你需要在启动时设置配置如下

 public partial class Startup
    {
        public static IConfiguration Configuration;

        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }
    ...
}

然后如下访问

Configuration.GetConnectionString("System")

您还应该按如下所示布置连接字符串。

"ConnectionStrings": {
    "System": "{connection String}"
  }

如果需要,这将允许使用多个字符串,但即使只有一个字符串也能正常工作。

编辑:一旦获得字符串,正如 ColinM 在他的回答中所说,您需要使用 class 注册字符串,您可以将其注入 classes。在启动如下。

services.AddSingleton<IConnectionStringFactory, ConnectionStringFactory>(serviceProvider => new ConnectionStringFactory(Configuration.GetConnectionString("System")));

你的连接字符串class...

public class ConnectionStringFactory : IConnectionStringFactory
{
    private readonly string _connectionString;

    public ConnectionStringFactory(string connectionString)
    {
        _connectionString = connectionString;
    }

    public string Invoke()
    {
        return _connectionString;
    }
}

像这样注入你的class...

public class ClassName
{
    private readonly IConnectionStringFactory _connectionStringFactory;

public ClassName(IConnectionStringFactory connectionStringFactory)
    {
        _connectionStringFactory = connectionStringFactory;
    }

...
}

您的界面可以像下面这样简单

public interface IConnectionStringFactory
{
}

您不需要使用界面,但我推荐这种方法

您应该在启动时使用配置 =>

    public void ConfigureServices(IServiceCollection services)
    {
       var section = Configuration.GetSection("ConnectionString");
       var value= Configuration.GetValue<string>("ConnectionString")
    }

根据您在上下文中 OnConfiguring 覆盖中设置连接字符串的要求,您可以使用以下方法。

更新您的 appsettings.json 配置文件,为您的数据库选项包含一个新的 JSON 对象

{
    "Logging": {
        "LogLevel": {
            "Default": "Warning"
        }
    },
    "DatabaseOptions": {
        "ConnectionString": "<Connection String>"
    }
}

创建模型 class,您的 DatabaseOptions 配置将映射到

public class DatabaseOptions
{
    public string ConnectionString { get; set; }
}

然后更新您的 Startup class' ConfigureServices 方法以注册 IOptions<DatabaseOptions>

的实例
public void ConfigureServices(IServiceCollection services)
{
    services.AddMvc();
    services.Configure<DatabaseOptions>(Configuration.GetSection("DatabaseOptions"));
}

最后,更新您的上下文构造函数以注入您的 IOptions<DatabaseOptions> 实例,ASP.NET 只要您在服务集合中注册上下文,Core 就会为您处理依赖项注入。

public class MyContext
{
    private readonly DatabaseOptions databaseOptions;

    public MyContext(DbContextOptions<MyContext> options, IOptions<DatabaseOptions> databaseOptions)
        : base(options)
    {
        this.databaseOptions = databaseOptions.Value;
    }

    protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
    {
        //here I need my connection string
        optionsBuilder.UseMySql(databaseOptions.ConnectionString);
    }
}

就我个人而言,当 class 将与 [=19] 一起使用时,我不喜欢在名称中使用 Options 命名 classes =],但作为开发人员,我们可能会花费大量时间来考虑 class 和变量名,请随意重命名。