Common Operations on the Web. config configuration file

Source: Internet
Author: User
Tags reflector xpath connectionstrings

Common configuration file operations include:

L read

L modify

L put the configuration section in web. config in a separate file

L encrypt a Section

L add custom sections

The namespace used to operate the web Configuration file (including machine. config and web. config) is System. Web. Configuration. The main application class is WebConfigurationManager. Let's take a look at the members of the WebConfigurationManager class. (You can use MSDN to check the Reflector of Lutz Roeder)

 

Figure 1 WebConfigurationManager class member

3.2.1 read
 

Figure 2 attributes and methods used for reading in the WebConfigurationManager class

3.2.1.1 read ettings and connectionStrings
In the WebConfigurationManager class, we first notice the two attributes etettings and ConnectionStrings. These two attributes are used to perform operations on the two pieces of appSettings and connectionStrings in the web. config file we saw earlier. The following shows how to use it.

The code for operating the deleettings section is as follows:

Using System. Web. Configuration;

....

String message;

Message = WebConfigurationManager. receivettings ["message"];

...
 

Code of the connectionStrings section:

Using System. Web. Configuration;

....

String connectionString =

WebConfigurationManager. ConnectionStrings ["pubs"]. ConnectionString;

...
 

3.2.1.2 read other sections
Reading other sections in. NET is troublesome. We need to use the GetSection () function. The GetSection () function is used to retrieve the specified configuration section from the configuration file of the current web application. The GetSection () function has two reloads. Here we will introduce GetSection (string sectionName ). This function parameter sectionName is the XPath expression used to find nodes (for more information about XPath expressions, see other documents ). The first thing we need to know here is. all configuration sections in. NET correspond to a class, for example, the web. in the config file, the etettings section corresponds to the AppSettingsSection class, while the connectionStrings section corresponds to the ConnectionStringsSection class. With the Reflector of Lutz Roeder, we can easily know all section classes. See.

 

Figure 3 inherits the section classes of the ConfigurationSection class

We can find that the compilation section corresponds to System. web. configuration. compilationSection class. The authentication section corresponds to System. web. configuration. authenticationSection class. The identity section corresponds to System. web. configuration. identitySection class.

Example 1:

Protected void readImpersonationButton_Click (object sender, EventArgs e)

{

IdentitySection section;

Section = WebConfigurationManager. GetSection ("system. web/identity ")

As IdentitySection;

If (section! = Null)

{

WriteMessage ("Impersonate =" + section. Impersonate );

}

}

Private void WriteMessage (string message)

{

// Add a PlaceHolder control named messagePlaceHolder to the page.

HtmlGenericControl generic = new HtmlGenericControl ();

Generic. InnerHtml = message;

MessagePlaceHolder. Controls. Add (generic );

}
 

In the above example, the XPath expression system. web/identity can be used to guess what it means. For the IdentitySection class, you need to use the Reflector lookup or MSDN lookup of Lutz Roeder.

Example 2: (example on MSDN) This example shows a section that can be accessed from a Web application or console application.

// Show the use of GetSection (string ).

// It gets the connectiobStrings section.

// If called from within a client application,

// The GetSection (string) gets the default connectionStrings

// Section from the machine. config.

// If called from within a Web aplication it gets

// Section from the configuration file located at

// Application current level.

Static void GetSection1 ()

{

// Get the connectionStrings section.

ConnectionStringsSection connectionStringsSection =

WebConfigurationManager. GetSection ("connectionStrings ")

As ConnectionStringsSection;

// Get the connectionStrings key, value pairs collection.

ConnectionStringSettingsCollection connectionStrings =

ConnectionStringsSection. ConnectionStrings;

// Get the collection enumerator.

IEnumerator connectionStringsEnum =

ConnectionStrings. GetEnumerator ();

// Loop through the collection and

// Display the connectionStrings key, value pairs.

Int I = 0;

Console. WriteLine ("[Display the connectionStrings]");

While (connectionStringsEnum. MoveNext ())

{

String name = connectionStrings [I]. Name;

Console. WriteLine ("Name: {0} Value: {1 }",

Name, connectionStrings [name]);

I + = 1;

}

Console. WriteLine ();

}
 

There are several other examples on MSDN for reference.

3.2.2 modify
As shown in figure 2, several static functions such as OpenWebConfiguration () and OpenMachineConfiguration () are used to open a configuration file (which corresponds to the web. config and machine. config.

Example: Modify compilation under system. web (false-> true; or true-> false ).

Protected void toggleDebugButton_Click (object sender, EventArgs e)

{

Configuration config;

Config = WebConfigurationManager. OpenWebConfiguration ("~ ");

CompilationSection compilation;

Compilation = config. GetSection ("system. web/compilation ")

As CompilationSection;

If (compilation! = Null)

{

Compilation. Debug =! Compilation. Debug;

Config. Save ();

WriteMessage ("Debug setting is now:" + compilation. Debug );

}

}

Note:

1. You must have the permission to modify the file. Generally, the network service and ASPNET accounts do not have the permission to modify the file and directory.

2. When ASP. NET is running, the Runtime is watching the changes in the web. config file. Once the file is modified, the entire application creates a new instance and reloads it. If you frequently modify the web. config file, the program performance will be greatly affected.

3. If you need to modify the configuration frequently, put the configuration section in a separate file.

3.2.3 place the configuration section in web. config in a separate file
We can put any configuration section into an independent file. The advantage of placing the configuration section in web. config in a separate file will be discussed later. First, let's see how to do it. The example starting from this article is as follows.

Example:

Web. config file

<? Xml version = "1.0"?>

<Configuration xmlns = "http://schemas.microsoft.com/.NetConfiguration/v2.0">

<Maid configSource = "maid. config"/>

<ConnectionStrings configSource = "connections. config"/>

<System. web>

<Compilation debug = "true"/>

<Authentication mode = "Windows"/>

<Identity impersonate = "true"/>

</System. web>

</Configuration>
 

AppSettings. config file:

<Deleetask>

<Add key = "message" value = "Hello World! "/>

</AppSettings>
 

Connections. config file:

<ConnectionStrings>

<Add name = "AdventureWorks" connectionString = "..."/>

<Add name = "pubs" connectionString = "..."/>

</ConnectionStrings>
 

Advantages of using external configuration files:

1. You can set different configurations based on different environments, such as the development environment, test environment, and formal environment to configure different database connections.

2. permission management. For example, you can lock web. config so that some people do not modify it, but only allow it to modify the permissions of the appSettings. config file.

3. Using the external configuration file, you can also control whether the application restarts after modification. Generally, when we modify the web. config file, the application generates a new instance and restarts. If it is a separate configuration file, you can control whether to restart or not.

Configuration method: Configure in machine. config. The Machine. config file is generally in the C: \ WINDOWS \ Microsoft. NET \ Framework \ v2.0.50727 \ CONFIG directory. Open the machine. config file as follows:

 

Figure 4 machine. config file content

Figure 4 shows that some elements have the restartOnExternalChanges attribute. If it is set to false, the external file will not be restarted after modification. If it is set to true, it will be restarted.

3.2.4 encrypt a Section
It is quite simple to encrypt a section in. NET2.0.

In the configuration file, some information is not expected to be seen by others. For example, the <connectionStrings> section may contain the username and password used to connect to the database. The <identity> section may also contain the user name and password.

Note: Some sections may contain passwords but cannot be encrypted. For example, in the <processModel> section, you can use the aspnet_setreg.exe tool to save the password.
 

The following example shows how to encrypt and decrypt a file. Note: The words used for encryption and decryption here are protect and unprotect. Note: In actual applications, we do not need to call the decryption function explicitly. In the running City, the program automatically calls decryption when it reads the encrypted configuration section.

Protected void toggleEncryptionButton_Click (object sender, EventArgs e)

{

Configuration config;

Config = WebConfigurationManager. OpenWebConfiguration ("~ ");

ConnectionStringsSection section;

Section = config. GetSection ("connectionStrings ")

As ConnectionStringsSection;

If (section. SectionInformation. IsProtected)

{

Section. SectionInformation. UnprotectSection ();

}

Else

{

Section. SectionInformation. ProtectSection ("DataProtectionConfigurationProvider ");

}

Config. Save ();

WriteMessage ("connections protected =" + section. SectionInformation. IsProtected );

}
 

This code is used to encrypt and decrypt the connectionStrings section. If the data is encrypted (determined by the IsProtected attribute), the data is decrypted. Otherwise, the opposite is true. The UnprotectSection () and protectSection () functions are called respectively.

The following are the changes to related files.

The contents of the connectionStrings. config file before encryption are as follows:

 

Figure 5 contents of the connectionStrings. config file before encryption

The contents of the connectionStrings. config file after encryption are as follows:

 

Figure 6 connectionStrings. config file after Encryption

We can compare the changes to the results and learn about the changes.

However, in the code snippet above, we also need to know about the encryption provider. There are currently two types of encryption providers: DataProtectionConfigurationProvider and RSAProtectedConfigurationProvider. DataProtectionConfigurationProvider uses Windows Data Protection API (DPAPI) to provide machine-related encryption and decryption. That is to say, on which machine we encrypt, we can only decrypt on that machine. You can only use DataProtectionConfigurationProvider to decrypt data on other machines.

3.2.5 add custom configuration section
When we need to configure a large amount of data, in order to facilitate management. We may need to add custom configuration sections. The following is a simple example.

<Configuration>

<ConfigSections>

<Section name = "Logging" type = "System. Configuration. NameValueSectionHandler"/>

</ConfigSections>

<Logging>

<Add key = "File Name" value = "MyApp. log"/>

<Add key = "MessageColumns" value = "5"/>

<Add key = "MaxFileSize" value = "40000000000000"/>

</Logging>

</Configuration>
 

 

This article from the CSDN blog, reproduced please indicate the source: http://blog.csdn.net/ouhaiyong/archive/2006/12/22/1453724.aspx

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.