Adnan Mohsin January 04, 2017 Comments 2.00

"What is web.config in ASP.NET MVC and how to use appSettings and Connection string

In this tutorial i will explain what is web.config file and how to apply configurations in ASP.Net MVC keeping in view the best practices. Configuration is the first service which is provided by the ASP.Net platform. Although this topic is not much interesting to learn configuration , however this feature is essentially rich and helps the developer avoid various coding disasters. Once the programmer understands the ASP.Net Configuration , he can apply this knowledge to all kinds of web applications so pay enough time to understand.In this tutorial you will learn:

  1. What is ASP.Net Configuration?
  2. The Configuration Hierarchy
  3. How to use "application settings"?
  4. How to use "connection strings"?

1.    What is ASP.Net Configuration?

It provides a collection of classes and files which control the behavior of the ASP.NET application basic foundation and services and also the MVC framework. It is quiet easier to use the built in configuration support than writing your own settings instead. There are also some excellent features which eases the application development in default settings.

2.    The Configuration Hierarchy

Most of the web developers only require editing the Web.config file in the top level of visual studio project, but this is the only one of the hierarchy files which is used by ASP.NET. When the application is first started ASP.Net starts from the top of sequence and flows down to work. each level is assigned its role and scope which is slightly narrow , and the total effect is to allow lower level config files to over-ride the preceding ones. The application-level Web.config file—the one in the root folder of Visual Studio—is close to the bottom of  the hierarchy and relies on bunch of settings that have been defined in higher-level files.

Hierarchy of Configuration files in ASP.NET Platform

3.    How to use "application settings"?

   Application settings are just key-value pairs and are used to extend the configuration to define values that are specific to an application. Following Listing shows the application settings that I added to the application-level Web.config file (the one that is at the root level in the Visual Studio project).

<?xml version="1.0" encoding="utf-8"?>
<configuration>
<appSettings>
    <add key="webpages:Version" value="3.0.0.0" />
    <add key="webpages:Enabled" value="false" />
    <add key="ClientValidationEnabled" value="true" />
    <add key="UnobtrusiveJavaScriptEnabled" value="true" />
    <add key="defaultCity" value="Mexico"/>
    <add key="defaultCountry" value="USA"/>
    <add key="defaultLanguage" value="English"/>
</appSettings>
Reading appSettings values:

We can read the appSettings values by referencing System.Web.Configuration in contrlloer class as shown in the following listings. 

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

namespace Example.Controllers
 {
    public class HomeController : Controller
    {
        public ActionResult Index()
            {
            Dictionary<string, string> configData = new Dictionary<string, string>();
            foreach (string key in WebConfigurationManager.AppSettings) {
                configData.Add(key, WebConfigurationManager.AppSettings[key]);
            }
            return View(configData);
        }
    }
}

4.    How to use "connection strings"?

The second setting which is frequently defined in configuration file is connection string. You must have defined connection string in your MVC framework because they are most often required to connect to the databases. It provides connection details for the database. Although most of the connection strings are required to configure database connections, they actually represent  feasible  mechanism that can be utilized  to describe any kind of connection to an external resource ie any database.There are two parts of a connection string: the name of the provider class that will be required to establish the connection and the string that the provider will require to do its work. The format of the string isn’t standardized because it has to make sense only to the provider, but in following Listing I have added a connection string to the application-level Web.config file that uses a familiar format.

<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <appSettings>
    <add key="webpages:Version" value="3.0.0.0" />
    <add key="webpages:Enabled" value="false" />
    <add key="ClientValidationEnabled" value="true" />
    <add key="UnobtrusiveJavaScriptEnabled" value="true" />
    <add key="defaultCity" value="Mexico"/>
    <add key="defaultCountry" value="USA"/>
    <add key="defaultLanguage" value="English"/>
  </appSettings>
  <connectionStrings>
    <add name="csharptutor" connectionString="Data Source=(localdb)\v11.0;Initial
         Catalog=myexampledb;Integrated Security=True"
         providerName="System.Data.SqlClient"/>
  </connectionStrings>
Reading Connection Strings

We can read the connection string values  in contrlloer class as shown in the following listing:

public ActionResult ReadConnStr()
      {
            Dictionary<string, string> configData = new Dictionary<string, string>();
            foreach (ConnectionStringSettings cs in
                    WebConfigurationManager.ConnectionStrings) {
                configData.Add(cs.Name, cs.ProviderName + " " + cs.ConnectionString);
            }
            return View(configData);
        }

public ActionResult GetSingle()
        {
            return View((object)WebConfigurationManager
                .ConnectionStrings["csharptutor"].ConnectionString);
        }

Design
8/10
Support
2/10
Development
4.5/10

7.5

Awesome
3.50
Summary

This article is to provide you overview of ASP.Net Configuration file which is used as web.config in ASP.Net MVC project.I have covered appsettings and connection string elements of configuration.

Search widget

Banner

Latest posts

Design Patterns Design Patterns in Programming

What is a Design Pattern? According to MSDN, "A design pattern is a description of a set of interacting classes that provide a framework for a solution to a generalized problem in a specific context or environment. In other words, a pattern suggests a solution to a particular problem or issue in object-oriented software development.”

May 05, 2017 16 0

C# Ref and Out parameters in C Sharp

This tutorial explains the concepts of Ref and Out Keywords in C # programming. These two keywords are also frequently asked in most interviews.

January 15, 2017 16 0

WPF Vector Graphics in WPF

In this article, I will discuss how we can create a Line, Rectangle, ellipse and Polygon control in WPF at design-time using XAML and at run-time using C#.I will also explain their properties to format such as fill property. After that, i will show you to set an image as the background of any shape object.

January 08, 2017 16 0

C# What is the difference between an Abstract Class and an Interface

One question is always out there in most interviews. What is the difference between an Abstract Class and an Interface and why do you use one over the other? It seems like a simple question but most often, the answer to this question is not sufficient for the interviewer and can cost a job. So, I have decided to write an article about them and have tried to explain it.

December 26, 2016 16 0