这个问题通常是由于appsetting.json转换文件中的属性名称不匹配而导致的。例如,属性名称在源文件和转换文件中不一致。
针对这个问题,可以使用以下代码示例解决:
1.在 appsettings.Development.json 文件中定义以下内容:
{ "Logging": { "LogLevel": { "Default": "Information", "Microsoft": "Warning", "Microsoft.Hosting.Lifetime": "Information" } }, "AppSettings": { "Database": { "ConnectionString": "Server=(localhost);Database=MyDatabase;User Id=myuser;Password=mypassword" } } }
2.在 appsettings.Production.json 文件中定义以下内容:
{ "AppSettings": { "Database": { "ConnectionString": "Server=(prod-server);Database=MyDatabase;User Id=myuser;Password=mypassword", "UseConnectionPooling": true } } }
public Startup(IConfiguration configuration, IWebHostEnvironment env) { Configuration = configuration;
var builder = new ConfigurationBuilder() .SetBasePath(env.ContentRootPath) .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true) .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true, reloadOnChange: true) .AddEnvironmentVariables();
Configuration = builder.Build();
// Get the AppSettings section var appSettingsSection = Configuration.GetSection("AppSettings");
// Configure the database options
services.Configure
4.最后,在 ConfigureServices 方法中定义 DatabaseOptions,如以下代码所示:
public void ConfigureServices(IServiceCollection services)
{
services.AddDbContext
services.Configure
通过以上代码,添加的 Program.cs 的内容为:
using Microsoft.AspNetCore.Hosting; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.Hosting; using Microsoft.Extensions.Logging;
namespace TestConfiguration