3

I'm trying to set up my WebAPI project to dynamically grab the correct connection string depending on what environment the project is deployed to in Azure. I used the following Stack Overflow post as an example of sorts: Accessing SqlServer conn strings in Azure

In my code, I'm trying to set this value, but it's coming back null.

private static readonly string _connStr =
    Environment.GetEnvironmentVariable("SQLAZURECONNSTR_conn");

And in my web.config, the connection string is stored as follows:

<connectionStrings>
  <add name="conn" connectionString="{Connection string stuff}" />
</connectionStrings>

In my deployment location up on Azure, I set the connection string in the Application Settings section of my app service. My problem is that while testing locally, my connection string value isn't getting set in the aforementioned line of code _connStr.

I was made to understand that I didn't need to add the SQLAZURECONNSTR_ segment in my web.config and that the Environment.GetEnvironmentVariable() would detect the environment, then grab the correct connection string. I'm beginning to suspect that is incorrect though. Am I missing something? I'd appreciate any help.

1 Answer 1

2

You have misunderstood how the settings work.

To get the setting you should use

string connStr = ConfigurationManager.ConnectionStrings["conn"].ConnectionString;

Azure will change the setting on the fly to whatever you set there. In addition, it also sets an environment variable called SQLAZURECONNSTR_conn. But this will not be set in your local environment unless you set it. The setting itself won't create it.

And since this is a connection string, be sure to set it in the Web App's Connection Strings section, not App Settings!

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.