Reputation: 1789
I'm trying to pull data from the web config file as outlined by this msdn resource.
Here is my code:
System.Configuration.Configuration activeCampaignApiSetting1 =
System.Web.Configuration.WebConfigurationManager.OpenWebConfiguration(null);
if (activeCampaignApiSetting1.AppSettings.Settings.Count > 0) {
System.Configuration.KeyValueConfigurationElement activeCampaignApiKeySetting =
activeCampaignApiSetting1.AppSettings.Settings["ActiveCampaignApiKey"];
if (activeCampaignApiKeySetting != null) {
activeCampaignApiKey = activeCampaignApiKeySetting.Value;
}
System.Configuration.KeyValueConfigurationElement activeCamapignApiUrlSetting =
activeCampaignApiSetting1.AppSettings.Settings["ActiveCampaignApiUrl"];
if (activeCamapignApiUrlSetting != null) {
activeCampaignApiUrl = activeCamapignApiUrlSetting.Value;
}
}
When I try to instantiate this class:
var acs = new Acs(activeCampaignApiKey, activeCampaignApiUrl);
it throws an exception telling me that the values are blank.
The values in the web config file are there:
<add key="ActiveCampaignApiKey" value="apikey_removed" />
<add key="ActiveCampaignApiUrl" value="apiurl_removed" />
Anyone know where I may be going wrong? Cheers
Upvotes: 1
Views: 714
Reputation: 1789
Ok so I have a better solution,
As I'm working with nopCommerce I need to use:
private readonly ISettingService _settingService = EngineContext.Current.Resolve<ISettingService>();
string apikey = _settingService.GetSettingByKey<string>("apikey_removed");
string apiurl = _settingService.GetSettingByKey<string>("apiurl_removed");
As outlined in this forum thread
Then in the administration backend under configuration > settings > all settings I add the key there.
This is a much better solution because if the api key or url ever need to be changed it can be done through the nopcommerce administration panel. rather than rebuilding/publishing the solution to a web server.
Hope this helps someone :)
Upvotes: 0
Reputation: 62290
If they are appSetting inside web.config, you can access them via ConfigurationManager.AppSettings
.
<?xml version="1.0"?>
<configuration>
<configSections>
<appSettings>
<add key="ActiveCampaignApiKey" value="apikey_removed" />
<add key="ActiveCampaignApiUrl" value="apiurl_removed" />
</appSettings>
</configSections>
</configuration>
string activeCampaignApiKeySetting
= ConfigurationManager.AppSettings["ActiveCampaignApiKey"];
string activeCamapignApiUrlSetting
= ConfigurationManager.AppSettings["ActiveCampaignApiUrl"];
Please make sure you reference System.Configuration
, and include using System.Configuration;
directive.
FYI: They return string value (not key value pair).
Upvotes: 5