Reputation: 3727
Take the code below
Web.config:
<configuration>
<appSettings>
<add key="accesstoken:case1" value="00b8d5e4-a318-4f2d-bd5b-e7832861dbb6" />
</appSettings>
</configuration>
Controller.cs:
public JsonResult GetSomething(string token = "")
{
switch (token)
{
case System.Configuration.ConfigurationManager.AppSettings["accesstoken:case1"]:
...
case ...:
}
}
So here I get an error for case1 saying a constant value is expected. And I had the impression that AppSettings was constant. But because it's being accessed in the way it is I suppose a constant is impossible.
But I really like switch/cases instead of having a bunch of if/elses, so is it possible to access AppSettings to get a constant value?
Upvotes: 0
Views: 2509
Reputation: 23220
Constant inside a file doesn"t mean it is also a constant in the code. Constant in code always have a keyword const
. It is not the same. Values configured inside the file settings can be modifiied during execution of your application. Constant fields can't be modified during execution.
A solution to achieve what you need to do without a bunch of if-else
or switch-case
is at startup of you application to load a dictionary that will contain all key (e.g. starting with accesstoken:*
)
public static Lazy<IDictionary<string, string>> AppSettingsAccessTokens = new Lazy<IDictionary<string, string>>(() =>
{
return ConfigurationManager.AppSettings.AllKeys.Where(p => p.StartsWith("accesstoken:")).ToDictionary(p => p, p => ConfigurationManager.AppSettings[p]);
});
And finally in your GetSomething
method you do like:
public JsonResult GetSomething(string token = "")
{
var accessTokenSettingKey = AppSettingsAccessTokens.Value.Values.FirstOrDefault(p => p == token)?.Key;
// ....
}
Upvotes: 2