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.

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 stackoverflow.com/questions/31453495/… Commented Sep 6, 2018 at 5:50

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.