0
<appSettings>
    <add key="ApiKey" value="xyz"/>
</appSettings>

<system.net>
  <mailSettings>
    <smtp deliveryMethod="Network">
      <network host="smtp.cloudmailapp.com" port="587" userName="user@gmail.com" password="xyz" />
    </smtp>
  </mailSettings>
</system.net>

As you can see, the API key "xyz" appears twice, hardcoded.

Can I use code here? I'd like to be able to call

WebConfigurationManager.AppSettings["ApiKey"]

within the Web.config file, or something similar.

nmit026
  • 3,024
  • 2
  • 27
  • 53

2 Answers2

1

I think the short answer to your question is no. The config files cannot include C# code like you are trying to add out of the box.

I did find another post that asks a question very similar to this. Its from a few years back, but there is a lot of feedback in it that looks like it may apply here. Rather than trying to summarize the top answer, I will just add a link. Variables within app.config/web.config

Community
  • 1
  • 1
1

I am not sure what your workflow is to add variables to your config file, but perhaps as part of that you could run something over the top of the web.config to ensure you don't have duplicates.

While it is convenient to place configuration values in the web.config it was not really the place to store application settings. There are a number of reasons for this:

  • Maintainability (Your duplicate issue is one)
  • Security (unless you encrypt your web.config)
  • Changes to web.config restart the .NET application

It is far better to place them into the database and retrieve them from there. Once you are dealing with the database you can set your indexes so that you do not allow duplicates and so on.

TheEdge
  • 9,291
  • 15
  • 67
  • 135
  • Those are good points. Using Azure, you can set values in the portal that will override values in the web.config at runtime. That doesn't solve my duplicate issue, but it's a tiny problem in the scheme of things. Also for a team of one or two, secrets in the source code aren't an issue. – nmit026 May 10 '16 at 07:03
  • Its not secrecy, its security. If you web.config file is compromised anyone with that file now has access credentials to databases etc. – TheEdge May 11 '16 at 23:05
  • By secrets I meant keys and values. If that happens, then it's probably game over anyway: http://stackoverflow.com/questions/4434969/what-is-the-point-of-encrypting-the-web-config-asp-net and http://stackoverflow.com/questions/676292/asp-net-web-config-encryption. Like I said, using Azure the web.config could contain test values which are overwritten at runtime when deployed. The production values are set in the portal. But you're right, it is more thorough to encrypt as well, even if they're just test values. – nmit026 May 12 '16 at 22:00