配置" prod"和" dev" ASP.NET核心应用程序

时间:2017-10-11 10:07:08

标签: asp.net-core asp.net-core-2.0 asp.net-core-configuration

我尝试设置" dev"和" prod"我的ASP.NET Core 2.0应用程序的环境,但它不起作用......这是我的配置:

appsettings.json内容(与appsettings.Development.json完全相同)

{
  "Logging": {
    "IncludeScopes": false,
    "LogLevel": { "Default": "Warning" }
  },
  "ConnectionStrings": {
    "MyAppContext":     
      "...AccountName=MyApptables4dev; AccountKey=xxxxxx==;EndpointSuffix=core.windows.net"
  },
  "Authentication": {
    "AzureAd": {
      "AADInstance": "https://login.microsoftonline.com/",
      "CallbackPath": "/signin-oidc",
      "ClientId": "xxxxxxx",
      "Domain": "MyAppapp-dev.azurewebsites.net",
      "TenantId": "yyyyyyy"
    }
  }
}

appsettings.Production.json 只是连接字符串和域名更改:

"MyAppContext":"...AccountName=MyApptables4dev;AccountKey=yyyyyy==;EndpointSuffix=core..."

"Domain": "MyAppapp.azurewebsites.net",

Startup.cs

public Startup(IHostingEnvironment env)
{
    var builder = new ConfigurationBuilder()
        .SetBasePath(env.ContentRootPath)
        .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
        .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true, reloadOnChange: true);

    if (env.IsDevelopment())
    {
        builder = builder.AddUserSecrets<Startup>();
    }

    builder.AddEnvironmentVariables();
    Configuration = builder.Build();
}

public void ConfigureServices(IServiceCollection services)
{
    // Adds services required for using options.
    services.AddOptions();

    // Register the IConfiguration instance which "ConnectionStrings" binds against.
    //services.Configure<ConnectionStrings>(Configuration.GetSection("ConnectionStrings"));
    services.Configure<AppSecrets>(Configuration);
    services.AddSingleton<ITableRepositories, TableClientOperationsService>();
    // ...

secrets.json(位于“用户”文件夹中)内容

{
  "MyAppTablesConnectionString": "DefaultEndpointsProtocol=https;AccountName=myapptables4dev;AccountKey=xxx==;EndpointSuffix=core.windows.net"
}

最后是访问数据库的类(在我的情况下是AzureTables)

public class TableClientOperationsService : ITableRepositories
{
    // ... 

    public TableClientOperationsService() { }
    public TableClientOperationsService(IOptions<AppSecrets> optionsAccessor)
    {
        tables = new Dictionary<string, CloudTable>();            
        // 'null' in 'prod'!
        connectionString = optionsAccessor.Value.MyAppTablesConnectionString; 
    }

知道MyAppTablesConnectionString是&#34; null&#34;在&#34; Production&#34;中,问题可能来自那里,但我不知道如何使它与MyAppContextMyAppTablesConnectionString连接字符串一起工作......

1 个答案:

答案 0 :(得分:1)

因此,您的代码会从MyAppTablesConnectionString设置中读取值:

connectionString = optionsAccessor.Value.MyAppTablesConnectionString; 

但是根据提供的信息,只有dev env具有此设置(通过secret.json定义并由builder = builder.AddUserSecrets<Startup>();读取)。

是的,生产环境得到null,因为设置未在任何配置源中定义:

  • 用户密码未与prod
  • 一起使用
  • appsettings个文件无法描述MyAppTablesConnectionString
  • 并且您不会通过env变量传递此值。