Programmatically manipulating web.config in ASP.NET 2.0 and ASP.NET 3.5
ASP.NET provides the Web Site Administration Tool to view and manage the configuration settings for your ASP.NET website. These configuration settings are stored in an xml file called web.config.
“web.config is an application configuration file used to define configuration settings such as connecting strings, authentication, authorization etc., for an ASP.NET application”
The tool provides an easy to use interface to edit the configuration settings. However this tool works well when you have to manually make changes. At times, there could be a possibility where we need to make changes to the web.config at runtime. For example: a user requesting to control the connecting string, change session timeouts and so on.
For this purpose, ASP.NET provides the Configuration API to programmatically manipulate the configuration settings in web.config. The API’s are contained in the System.Configuration and System.Web.Configuration namespaces. In fact, internally the Web Site Administration Tool uses the same API to edit configuration settings.
The WebConfigurationManager class in the System.Web.Configuration namespace is used to create a Configuration object. This object is used to read and write changes to the web.config file. Let us walk through a small example to understand how we can use the API to edit the configuration settings.
Step 1: Create a new website. Add a web.config file to your website (Right Click project > Add New Item > Web Configuration File. Keep the default name as Web.config and click Add).
Step 2: Make the following changes to your web.config
In your <system.web> tag, uncomment the <customError> tag. We will be reading and editing one of the attributes of this tag. The end result after removing the comments should be as shown below:
<authenticationmode="Windows" />
<!--
The <customErrors> section enables configuration
of what to do if/when an unhandled error occurs
during the execution of a request. Specifically,
it enables developers to configure html error pages
to be displayed in place of a error stack trace. -->
<customErrorsmode="RemoteOnly" defaultRedirect="GenericErrorPage.htm">
<errorstatusCode="403"redirect="NoAccess.htm" />
<errorstatusCode="404"redirect="FileNotFound.htm" />
</customErrors>
</system.web>
Step 3: We will now go ahead and make changes to the ‘defaultRedirect’ attribute of the <customErrors> tag, using the API we just discussed. For this purpose, add a textbox, label control and a button to the form. After adding the controls, the source view of Default.aspx would look similar to the following:
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title>Untitled Page</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:Label ID="lblErrorPage" runat="server" Text="Rename Error Page to :"></asp:Label>
<asp:TextBox ID="txtError" runat="server"></asp:TextBox><br />
<br />
<asp:Button ID="btnRename" runat="server" Text="Rename" /></div>
</form>
</body>
</html>
The textbox will be used to display the default value of the ‘defaultRedirect’ attribute.
Step 4: In the Page_Load, display the current default value of the ‘defaultRedirect‘ attribute. To do so, declare the objects for Configuration and WebConfigurationManager at form level and add the following code at Form_Load():
C#
Configuration configuration;
CustomErrorsSection section;
protected void Page_Load(object sender, EventArgs e)
{
configuration = WebConfigurationManager.OpenWebConfiguration("~");
section = (CustomErrorsSection)configuration.GetSection("system.web/customErrors");
txtError.Text = section.DefaultRedirect.ToString();
}
VB.NET
Private configuration As Configuration
Private section As CustomErrorsSection
Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs)
configuration = WebConfigurationManager.OpenWebConfiguration("~")
section = CType(configuration.GetSection("system.web/customErrors"), CustomErrorsSection)
txtError.Text = section.DefaultRedirect.ToString()
End Sub
As seen in the code above, an explicit conversion is required to the CustomErrorSection and then the GetSection() is used on the configuration object to read section value into the textbox.
Step 5: If you run the application, the textbox is populated with the default value of the ‘defaultRedirect ‘ attribute. If you haven’t changed the value in the web.config, the value displayed is ‘GenericErrorPage.htm’.
Step 6: Now let us see how to change this value. To do so, we use the same ‘section’ object and set the value on button click.
C#
protected void btnRename_Click(object sender, EventArgs e)
{
if (section != null)
{
section.DefaultRedirect = "SomePage.htm";
configuration.Save();
// display a message informing the user that value has changed
}
}
VB.NET
Protected Sub btnRename_Click(ByVal sender As Object, ByVal e As EventArgs)
If Not section Is Nothing Then
section.DefaultRedirect = "SomePage.htm"
configuration.Save()
' display a message informing the user that value has changed
End If
End Sub
Run the code and click on the Rename button. The ‘defaultRedirect’ section is set to a value and the Save() method is called on the configuration object to persist the changes in web.config. If you now open and view the web.config file, the ‘defaultRedirect’ will have a different value, ‘SomePage.htm’
Similarly you can edit other sections as well. You can view the other section classes in the System.Web.Configuration namespaces. Read more about this namespace over here.
As you saw, it is quiet easy to use the Configuration API to view and edit the configuration settings. Just keep in mind that making changes to the web.config restarts the webserver and invalidates the cache. So do not do it often. I would suggest you to try out some samples on your own. For example, edit the connection string or the app settings section in the web.config to a desired value, by exploring the namespaces mentioned in the article and exploring the WebConfigurationManager class.
I hope this article was useful and I thank you for viewing it.
This article has been editorially reviewed by Suprotim Agarwal.
C# and .NET have been around for a very long time, but their constant growth means there’s always more to learn.
We at DotNetCurry are very excited to announce The Absolutely Awesome Book on C# and .NET. This is a 500 pages concise technical eBook available in PDF, ePub (iPad), and Mobi (Kindle).
Organized around concepts, this Book aims to provide a concise, yet solid foundation in C# and .NET, covering C# 6.0, C# 7.0 and .NET Core, with chapters on the latest .NET Core 3.0, .NET Standard and C# 8.0 (final release) too. Use these concepts to deepen your existing knowledge of C# and .NET, to have a solid grasp of the latest in C# and .NET OR to crack your next .NET Interview.
Click here to Explore the Table of Contents or Download Sample Chapters!
Was this article worth reading? Share it with fellow developers too. Thanks!
Suprotim Agarwal, MCSD, MCAD, MCDBA, MCSE, is the founder of
DotNetCurry,
DNC Magazine for Developers,
SQLServerCurry and
DevCurry. He has also authored a couple of books
51 Recipes using jQuery with ASP.NET Controls and
The Absolutely Awesome jQuery CookBook.
Suprotim has received the prestigious Microsoft MVP award for Sixteen consecutive years. In a professional capacity, he is the CEO of A2Z Knowledge Visuals Pvt Ltd, a digital group that offers Digital Marketing and Branding services to businesses, both in a start-up and enterprise environment.
Get in touch with him on Twitter @suprotimagarwal or at LinkedIn