Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get a String value from web.config in MVC4

Tags:

I want to get a logFilePath value which I gave by hardcode in to appSettings. I am trying to reach the key value by

System.Configuration.Configuration rootWebConfig1 = System.Web.Configuration.WebConfigurationManager.OpenWebConfiguration(null);
System.Configuration.KeyValueConfigurationElement customSetting = rootWebConfig1.AppSettings.Settings["azureLogUrl"];
string pathValue =  customSetting.Value;

but I am getting null reference exception . How can I get the value from web.config file?

like image 538
iburak Avatar asked Aug 28 '13 09:08

iburak


People also ask

How to get the Web Config value 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.

Why we use connection string in Web Config?

It is a configuration file where you store all your application settings. With the help of it, connection string becomes configurable i.e without changing build you can change the database to be connected.

Where to put connection string?

Connection strings can be stored as key/value pairs in the connectionStrings section of the configuration element of an application configuration file. Child elements include add, clear, and remove.


2 Answers

Use:

string pathValue = ConfigurationManager.AppSettings["azureLogUrl"];

You do not need to cast this to string and check for nulls because documentation states:

Values read from the appSettings element of the Web.config file are always of type String. If the specified key does not exist in the Web.config file, no error occurs. Instead, an empty string is returned.

like image 85
juhan_h Avatar answered Sep 23 '22 03:09

juhan_h


You can get the value from web.config like this :

string pathValue = WebConfigurationManager.AppSettings["azureLogUrl"].ToString();
like image 21
Srinivas Avatar answered Sep 24 '22 03:09

Srinivas