0

I have created a .NetCore app in visual Studio and I want connection strings to be fetched from .json files, I have created the .json file launchSettings.json and added the configuration variables as shown.

 {
    "profiles": {
      "TwinSample": {
        "commandName": "Project",
        "environmentVariables": {
          "moduleEdgeHubConnectionString": "HostName=xxxx.xxx;DeviceId=xxxxx;ModuleId=xxxxxx;SharedAccessKey=xxxxx",
          "moduleEdgeAgentConnectionString": "HostName=xxxx.xxx;DeviceId=xxxx;ModuleId=xxxxx;SharedAccessKey=xxxxx"
        }
      }
    }
  }

when I execute it the connection strings in the .cs project is Null that is moduleEdgeHubConnectionString and moduleEdgeAgentConnectionString is not able fetch the values from .json files.

private static string moduleEdgeHubConnectionString = Environment.GetEnvironmentVariable("moduleEdgeHubConnectionString");
   private static string moduleEdgeAgentConnectionString = Environment.GetEnvironmentVariable("moduleEdgeAgentConnectionString");

I have also changed the properties like Build Action to Content and copy to output Directory to copy always.

can you please help me in resolving this.

Pooja
  • 1
  • Hi Pooja. Environment variables are (at least under windows) the values that you see when you type "set" in a command prompt. To read config from a json file, follow this https://stackoverflow.com/questions/31453495/how-to-read-appsettings-values-from-config-json-in-asp-net-core – gsharp Sep 06 '18 at 05:50

1 Answers1

1

In .net core, the default way of storing connection strings is in the section ConnectionStrings in the appsettings.json file.

"ConnectionStrings": {
    "moduleEdgeHubConnectionString": "HostName=xxxx.xxx;DeviceId=xxxxx;ModuleId=xxxxxx;SharedAccessKey=xxxxx",
    "moduleEdgeAgentConnectionString": "HostName=xxxx.xxx;DeviceId=xxxx;ModuleId=xxxxx;SharedAccessKey=xxxxx"
  }

To get the connectionstrings, use the frameworks IConfiguration interface extension method GetConnectionString()

var connectionstring = configuration.GetConnectionString("moduleEdgeHubConnectionString"):

If you need to have different connectionstrings for different environments you can always add new appsettings.<EnvironmentName>.json files. Look at this answer for more details

Marcus Höglund
  • 16,172
  • 11
  • 47
  • 69