Web.config File - ASP.NET MVC

I am going to explain about  Add/Update appSettings  in the Web.config file and how you can configure them to use in the application.

The simple following method from MDSN help you to read  any Key you sent it .


 public string  ReadSetting(string key)
        {
          var appSettings = ConfigurationManager.AppSettings;
           string result = appSettings[key] ?? "Not Found";
           return result;
        }

Last code ReadSetting , Just give your Key As String , will return the Value , if your key not exist will return to you "Not Found" String .

 

Add Key:

the next code will Add new Key with Value you give , but if there is any key is exist same as you add , just will Update the Value .

 static void AddUpdateAppSettings(string key, string value)
        {
             var configFile = WebConfigurationManager.OpenWebConfiguration("~/");
              var settings = configFile.AppSettings.Settings;
                if (settings[key] == null)
                {
                    settings.Add(key, value);
                }
                else
                {
                    settings[key].Value = value;
                }
                configFile.Save(ConfigurationSaveMode.Modified);
                ConfigurationManager.RefreshSection(configFile.AppSettings.SectionInformation.Name);
            }

 

After Add/Update your key , late say you need to use the Value some where in you C# code ,

Just use  it like the following Code :

String Str =ReadSetting(YourKey);

The question , how to read it  at Razor ??

Same way how we wrote it ReadSetting Method with some change ,

First add  System.Configuration to your References ,add it to your page :

 @using System.Configuration;

@{ 
    string  _YourValue = ConfigurationManager.AppSettings["YourKey"];
 }
 

I wish you find this post useful .



Share

Comments