简体   繁体   中英

Use different connectionString in production environment

i am new to Web-Development and so it is the first time, that I try to work with different environments.

So in my WebApp which is deployed on Azure I want to use a connectionString for my local database, when I am working locally in development environment, and when I deploy it, it should use a different database with another connectionString.

I have seen that there are two files in my Asp.Net Core project. "appsettings.json" and "appsettings.Development.json". If I understand correctly, app.dev.json should override the settings in app.json if I work in Development Environment. But it doesn`t. When I am debugging the app, to realy make sure that environment is set to development, it still uses appsettings.json.

You might be correct in term of Multiple Configuration Files . appsettings.json is a default configuration file that you can declare anything which includes both Development and Production . The merging pattern will be appsettings.{Environment}.json , then all matching keys will replace all keys in appsettings.json . Remembered the name Environment should be matched with ASPNETCORE_ENVIRONMENT to be used. In you case, app.dev.json so your environment should be dev (case-sensitive) instead of Development .

For example: We have a default `appsettings.json

{
    "ConfigurationString": "mongodb://localhost:27017",
    "MongoOptions": {
        "AllowWireUp": true,
        "AutoConnect": true
    }
}

Then you want to work in Development , you create appsettings.Development.json with content

{
    "ConfigurationString": "mongodb://192.168.1.1:27017",
    "MongoOptions": {
        "AllowWireUp": false
    }
}

Later when you run with Development , you will get combined file

{
    "ConfigurationString": "mongodb://192.168.1.1:27017",
    "MongoOptions": {
        "AllowWireUp": false
    }
}

Important : You will see MongoOptions.AutoConnect is false in Development because .NET Core merges two files based on first level key instead of merging nested. That means MongoOptions in appsettings.Development.json will replace entire your appsettings.json

There is a way to do that. I guess you are using Azure app service?. if so follow thease steps

  1. Create multiple app-settings files inside your project. (dev/ staging / uat / prod)
  2. These file names shoud be appsettings.Development.json appsettings.uat.json and appsettings.Production.json
  3. Each file should contain its own configurations.
  4. Then Go to your App service in azure > configuration > Application settings, add required prifix of your appsettings json file in Value filed in ASPNETCORE_ENVIRONMENT
  5. Restart app service. it should work now

在此处输入图像描述

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM