Monday, April 6, 2015

How to Read AppSettings Values from Web.config in MVC

In this post we describe Step by step How to Read AppSettings Values from Web.config in MVC.  
We implement here in just 5 minutes a C# method to read AppSettings from the web.config file, and display an error Alert using the Twitter Bootstrap , in case that some value was not found at the AppSettings :

How to Read AppSettings Values from Web.config in MVC

How to Read AppSettings Values from Web.config in MVC


First, let's add some Keys to the AppSettings in the web.config file:

Read AppSettings Values from Web.config in MVC


We'll use the Configuration namespace, so add the using as follows:

Read AppSettings Values from Web.config in MVC





Next, add the following method (to some MVC Controller, or to some specific Utilities class):
Values from Web.config in MVC
Here we read the AppSettings and, in case that the Key was not found, we throw an exception. This is the code to copy-paste:

private string ReadAppSettings(string key)
        {
            string value = ConfigurationManager.AppSettings[key];
            if (!String.IsNullOrEmpty(value))
            {
                return value;
            }
            else
                throw new Exception("AppSettings Values not found");
        }

Now, you can catch the exception, and return the Exception's Message inside some Tuple<>, as follows:

catch (Exception ex)
            {
                return new Tuple<bool, string>(false, ex.Message);

            }


Rebuild and run your MVC app, and browse to the MVC View.
This is a snapshot of an MVC View using the AppSettings Reader above:

AppSettings from Web.config


If you like this Bootstrap style, take a look at the following 5 minutes Tutorial about using the Bootstrap Alert component .



Happy programming.....

      by Carmel Schvartzman


כתב: כרמל שוורצמן