Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

appSettings and ConfigurationManager.AppSettings issue

I have searched the site, and while I found some very useful information, I couldn't figure out what is going on with my code. I have the following web.config:

<?xml version="1.0"?>
<configuration>
  <system.web>
  </system.web>

  <system.webServer>
  </system.webServer>

  <appSettings>
    <add key="APIKey" value="23e24c73feed7ca0f6afd876575842de"/>
    <add key="Secret" value="################################"/>
    <add key="Callback" value="http://localhost:55994/"/>
    <add key="Suffix" value="My3Words"/>
  </appSettings>
</configuration>

I have snipped out the stuff in system.web and system.webServer, but it's the default settings generated in an ASP.NET MVC app.

I am trying to access the keys in the section (this is a simple Facebook application using FB Connect).

In my code, I have the following line:

return ConfigurationManager.AppSettings["APIKey"];

and it is returning a null. I can't quite figure out what is going on. I have the requisite:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Mvc.Ajax;
using System.Configuration;

at the top of my .cs file. I have a very strong suspicion the error exists post-keyboard (i.e. in my brain), but I can't solve this one. Any ideas?

like image 900
Brandon Watson Avatar asked Apr 02 '09 23:04

Brandon Watson


People also ask

What is ConfigurationManager AppSettings?

it is a .net builtin mechanism to define some settings before the application starts, without recompiling. see msdn configurationmanager.

Can I use ConfigurationManager in .NET core?

ConfigurationManager was added to support ASP.NET Core's new WebApplication model, used for simplifying the ASP.NET Core startup code.

What is ConfigurationManager configuration?

The ConfigurationManager class enables you to access machine, application, and user configuration information. This class replaces the ConfigurationSettings class, which is deprecated. For web applications, use the WebConfigurationManager class.

How do I get AppSettings in C#?

To access these values, there is one static class named ConfigurationManager, which has one getter property named AppSettings. We can just pass the key inside the AppSettings and get the desired value from AppSettings section, as shown below.


1 Answers

Have you tried using the WebConfigurationManager:

return System.Web.Configuration.WebConfigurationManager.AppSettings["APIKey"];

This is the preferred option for using config files in a web app - it handles things like nested config files, etc.

like image 147
Zhaph - Ben Duguid Avatar answered Nov 02 '22 20:11

Zhaph - Ben Duguid