0

I'm trying to follow the guidance here for reading data from a web.config file.

I have the following in my web.config file:

<configuration>
<appSettings>
  <add key="customsetting1" value="customValue"/>
</appSettings>
<system.web>
<compilation debug="true" targetFramework="4.0" />
</system.web>
<system.data>
...

And to test the accessing of data I did the following:

@using System.Web
@using System.Configuration
@using System.Web.Configuration
@{
System.Configuration.Configuration rootWebConfig1 =
System.Web.Configuration.WebConfigurationManager.OpenWebConfiguration(null);

string value = (string) 
rootWebConfig1.AppSettings.Settings["customsetting1"].Value;

This led to the following error: System.NullReferenceException: Object reference not set to an instance of an object.

I have checked and found rootWebConfig1.AppSettings.Settings is not null, but rootWebConfig1.AppSettings.Settings["customsetting1"] is null.

What am I doing wrong?

David R
  • 994
  • 1
  • 11
  • 27
  • Just call `string value = ConfigurationManager.AppSettings["customsetting1"].ToString();` – Alisson Reinaldo Silva May 16 '17 at 23:41
  • Thanks. I did check earlier but only saw this question: http://stackoverflow.com/questions/6959024/cant-read-from-appsettings which didn't apply. Any idea why what I was trying to do didn't work? I was following MDSN page. – David R May 17 '17 at 01:03
  • What @Alisson wrote worked for me, Thanks! – David R May 17 '17 at 01:06

0 Answers0