Web. config configuration in Asp.net
By bendpoints 20101123
Directory
Web. config configuration in Asp.net... 1
1. configuration file storage location... 2
Ii. configuration file loading sequence... 2
3. Introduction to configuration file nodes... 3
1. <configsections>. 3
2. <appsettings>. 5
3. <connectionstrings>. 5
4. <system. Web>. 6
<Location>. 11
4. Some programming operations on the configuration file... 11
1. modify the configuration file at runtime... 11
2. Configure node encryption... 12
Web. config is an important file in Asp.net that stores configuration information (such as database connection strings. XML-based text files are stored in Web applications.ProgramBy default, it is not compiled into the DLL with the source file, and the runtime environment monitors whether it has changed at any time. Once there is a change, the system will automatically reload the latest content in it.
1. configuration file storage location
The default configuration file of. NET is saved in the "Windows directory \ Microsoft. NET \ framework \ Corresponding. Net version \ config" folder. The Windows directory varies with operating systems. Run "Echo % WINDIR %" on the command line to view the location of the Windows directory.
Figure: directory of Web. config
Asp.net has two very important configuration files, Machine. config and web. config, which are located under the config folder. These two files do not need to be manually maintained. Keep the default value. However, for the Asp.net application, there will be 0, 1 or more web. config configuration files, and the loading order of multiple configuration files will be problematic. This topic will be introduced in the following section.
Note: In the legend,. net3.0 and. net3.5 are only extended based on. net2.0, so the. net2.0 configuration file is useless. They do not even have the config directory.
Ii. configuration file loading sequence
When IIS starts the Asp.net website, it loads the configuration information in the configuration file and caches the information. It does not read the configuration file every time it is used, but IIS monitors the changes of these files at any time, when the quantity changes, it reads and caches the configuration information again.
When the Asp.net website is running, the node information in the configuration file is loaded as follows:
1) if there is a web. config file in the directory where the current running page is located, check whether the required node exists. If yes, return the result and stop the next search.
2) If the directory does not contain the web. config configuration or the configuration file does not have the desired node, search for the node in the configuration file of the configuration file in the upper-level directory where it is located until the root directory of the website. (Problem: the virtual directory in IIS6 is not the root directory)
3) If no Web exists in the root directory of the website. config or the required configuration node, switch to the "Windows directory \ Microsoft. net \ framework. net version \ config \ Web. config.
4) If no information is found in Article 1, continue to "Windows directory \ Microsoft. NET \ framework \ Corresponding. Net version \ config \ machine. config.
5) If you haven't found it, you can report an error.
There are two problems
1) the virtual directory in IIS6 is not the root directory.
2) when the system is running, will the Web. config be automatically loaded by manually adding a web. config file to a directory without web. config.
Iii. Introduction to configuration file nodes
Web. the config file is an XML text file whose root node is <configuration>. Common subnodes under this node include: <configsections>, <appsettings>, <connectionstrings> (Save the database connection string), <location>, and <system. web>. The following describes the configuration of each node.
1. <configsections>
The configsections element specifies the configuration section and the handler declaration. ASP. NET does not make any assumptions about how to process the settings in the configuration file, so this is necessary. However, ASP. NET delegates the processing of configuration data to the configuration section handler. The configuration structure information is as follows:
<Configsections>
<! -- Define the association between the configuration section handler and the configuration element. -->
<Section/>
<! -- Define the association between the configuration section handler and the configuration section. -->
<Sectiongroup/>
<! -- Remove references to inherited sections and groups. -->
<Remove/>
<! -- Removes all references to inherited sections and section groups. Only the sections and section groups added by the current section and sectiongroup elements are allowed. -->
<Clear/>
</Configsections>
Each section element identifies a configuration section or element and the associated configurationsection derived class that processes the configuration section or element. You can logically group section elements in the sectiongroup element to organize section elements and avoid naming conflicts. The section and sectiongroup elements are included in the configsections element.
If the configuration file contains the configsections element, the configsections element must be the first child element of the configuration element.
In the following example, we will write a custom configuration and complete its sectionhandler. First, we will add configsections under the <configuration> node.
<Configuration>
<Configsections>
<Sectiongroup name = "mysectiongroup">
<Section name = "mysection" requirepermission = "true"
Type = "configtest. sectionhandler. mysectionhandler, configtest. sectionhandler"/>
</Sectiongroup>
</Configsections>
<Mysectiongroup>
<Mysection>
<Add key = "key1" value = "value1"/>
<Add key = "key2" value = "value2"/>
<Add key = "key3" value = "value3"/>
<Add key = "key4" value = "value4"/>
<Add key = "key5" value = "value5"/>
</Mysection>
</Mysectiongroup>
<System. Web>
<Compilation DEBUG = "true" targetframework = "4.0"/>
</System. Web>
</Configuration>
Write a custom sectionhandler. We return a hashtable data for mysectionhandler.
Namespace configtest. sectionhandler
{
Public class mysectionhandler: iconfigurationsectionhandler
{
Public object create (Object parent, object configcontext, system. xml. xmlnode Section)
{
Hashtable ht = new hashtable ();
Foreach (xmlnode node in section. childnodes)
{
If (node. Name = "add ")
{
Ht. Add (node. attributes ["key"]. Value, node. attributes ["value"]. value );
}
}
Return HT;
}
}
}
Use this section on the page. The configurationmanager. getsection will get the hashtable returned by sectionhandler. Pay attention to the parameter structure.
Protected void page_load (Object sender, eventargs E)
{
Hashtable ht = configurationmanager. getsection ("mysectiongroup/mysection") as hashtable;
Foreach (dictionaryentry de in HT)
{
Response. Write (De. Key + "-" + De. Value + "<br> ");
}
}
2. <deleetask>
This node is mainly used to store some configuration information of the Asp.net application. You can also store the database connection string here, however. net2.0 provides the connectionstrings node, so we do not recommend that you store the database connection string here. The following is an image type instance.
<Deleetask>
<! -- Image type extension -->
<Add key = "imgtype" value = ".bmp example .jpg?.gif=.png"/>
</Appsettings>
The call method is as follows:
String imgtype = configurationmanager. receivettings ["imgtype"];
3. <connectionstrings>
Connectionstrings is similar to appsettings, but it is used to save the configuration database connection information. The following is an instance.
<Connectionstrings>
<Add name = "sqlserverconnstr" connectionstring = "Data Source = aron1; initial catalog = pubs; userid = sa; Password = asdasd;"/>
<Add name = "orcleconnstr" connectionstring = "provider = msdaora; Data Source = myoracledb; userid = username; Password = asdasd;"/>
</Connectionstrings>
The call method is as follows:
String connstr = configurationmanager. connectionstrings ["sqlserverconnstr"]. connectionstring;
4. <system. Web>
<System. web> is. NET application behavior configuration node, which contains many sub-nodes, many sub-nodes have been created. net has been configured. Here we only look at some important configuration nodes.
Ø <customerrors>
<Customerrors defaultredirect = "genericerror.htm" mode = "remoteonly">
<Error statuscode = "500" Redirect = "internalerror.htm"/>
</Customerrors>
The mode attribute has three values: On/Off/remoteonly. The default value is remoteonly. The error node specifies the HTTP status.Code.
Ø <authentication>
This node configures the ASP. NET authentication scheme, which is used to identify users who view ASP. NET applications. The mode attribute contains four authentication modes:
1. Windows (default)
Specify Windows authentication as the default authentication mode. It is used with any form of Microsoft Internet Information Service (IIS) authentication: basic, summary, integrated Windows authentication (NTLM/Kerberos) or certificate. In this case, your application delegates the authentication responsibility to the basic IIS.
2. Forms
Set ASP. NET form-based authentication to the Default Authentication Mode.
3. Passport
Set Microsoft Passport network authentication to the Default Authentication mode.
4. None
No authentication is specified. Your application only expects anonymous users; otherwise, it will provide its own authentication.
The following code example shows how to configure a site for form-based authentication, specify the cookie name for transmitting login information from the client, and specify the name of the logon page used when the initial authentication fails.. You must include the authorization Section to perform Forms authentication for all users and reject anonymous users from accessing the site.
<Configuration>
<System. Web>
<Authentication mode = "forms">
<Forms name = "401 Kapp" loginurl = "/login. aspx"/>
</Authentication>
<Authorization>
<Deny users = "? "/>
</Authorization>
</System. Web>
</Configuration>
Log on to login. aspx:
Formsauthentication. redirectfromloginpage (this. textbox1.text, true );
<Httphandlers>
Httphandlers can be used to map incoming requests to the corresponding handler Based on the specified URL and HTTP predicate in the request. Special processing can be performed on specified special files in a specific directory.
Next we will write a custom httphandle for all *. ABC folders under the path directory of the website.
Add to the configuration file first:
<Httphandlers>
<Add Path = "path/*. ABC" verb = "*" type = "configtest. httphandler. abchttphandler, configtest. httphandler"/>
</Httphandlers>
Write abchttphandler:
Namespace configtest. httphandler
{
Public class abchttphandler: ihttphandler, irequiressessionstate
{
Public bool isreusable
{
Get {return true ;}
}
Public void processrequest (httpcontext context)
{
Context. response. Write ("
Context. session ["test"] = "You call session in the abchttphandler container ";
Context. response. Write (context. session ["test"]);
}
}
}
System Call result:
Figure: httphandler Test
We can also use httphandlerfactory to switch handler. We first define two httphandler, httphandler1 and httphandler2. Then define a myhandlerfactory inherited from ihttphandlerfactory to dynamically switch httphandler. See the Code:
Namespace configtest. httphandler
{
Public class myhandlerfactory: ihttphandlerfactory
{
Public ihttphandler gethandler (httpcontext context, string requesttype, string URL, string pathtranslated)
{
If (URL. indexof ("1")>-1)
{
Return new httphandler1 ();
}
Else if (URL. indexof ("2")>-1)
{
Return new httphandler2 ();
}
// Return the default Handler
Return context. Handler;
}
Public void releasehandler (ihttphandler handler)
{
// Throw new notimplementedexception ();
}
}
Public class httphandler1: ihttphandler, irequiressessionstate
{
Public bool isreusable
{
Get {return true ;}
}
Public void processrequest (httpcontext context)
{
Context. response. Write ("
}
}
Public class httphandler2: ihttphandler, irequiressessionstate
{
Public bool isreusable
{
Get {return true ;}
}
Public void processrequest (httpcontext context)
{
Context. response. Write ("
}
}
}
Here is just a test. We set httphandler1 to exist in the URL and httphandler2 to exist. Otherwise, the system will return the default handler. We also need to add configuration items:
<Httphandlers>
<Add Path = "path/*. ABC" verb = "*" type = "configtest. httphandler. abchttphandler, configtest. httphandler"/>
<Add Path = "handlerfactory/*. *" verb = "*" type = "configtest. httphandler. myhandlerfactory, configtest. httphandler"/>
</Httphandlers>
An httphandler configuration item is added for all files in the handlerfactory directory. Let's run the test:
Figure: handlerfactory Test
Ø
When a request is transmitted in the pipeline, a series of events in the httpapplicaion object are triggered. we have seen these events in global. asax is released as an event. this method is specific to the application and may not always be what you want. if you want to create a generic httpapplication event hook that can be inserted into any web application, you can use httpmodule, Which is reusable and does not require specific language application code, only web. an entry in config.
<Httpmodules>
<Add name = "myhttpmodule" type = "configtest. httpmodule. myhttpmodule, configtest. httpmodule"/>
</Httpmodules>
Like httphandler, compile the httpmodule inherited from ihttpmodule:
Namespace configtest. httpmodule
{
Public class myhttpmodule: ihttpmodule
{
Public void dispose ()
{
Throw new notimplementedexception ();
}
Public void Init (httpapplication context)
{
Context. beginrequest + = new eventhandler (context_beginrequest );
}
Void context_beginrequest (Object sender, eventargs E)
{
Httpapplication application = (httpapplication) sender;
Httpcontext context = application. context;
Context. response. Write ("add beginrequest by myhttpmodule! ");
}
}
}
We just added one sentence on each page: Add beginrequest by myhttpmodule! Result:
Figure: httpmodule Test
<Location>
The location node is used to indicate the resources configured by the subnode. If you want to perform special processing on a directory in the Asp.net application, you can use this node. Here are two examples.
The following code example shows how to set the size limit of uploaded files on a specified page to 128 kb.
<Configuration>
<Location Path = "uploadpage. aspx">
<Httpruntime maxrequestlength = "128"/>
</Location>
</Configuration>
Add a watermark to the image in the specified directory:
<Configuration>
<Location Path = "Images">
<System. Web>
<Httphandlers>
<Add verb = "*" Path = "*. jpg" type = "imagehandler"/> <! -- Handler of image watermark settings -->
</Httphandlers>
</System. Web>
</Location>
</Configuration>
Iv. Some programming operations on the configuration file 1. Modifying the configuration file during runtime
Here we will demonstrate how to modify the deleteworker node:
Public static void setdeleetting (string key, string value)
{
Configuration Config = webconfigurationmanager. openwebconfiguration ("~ ");
Deleettingssection paietting = config. deleettings;
// If not, add
If (deleetting. settings [Key] = NULL)
{
Deleetting. settings. Add (Key, value );
}
Else // otherwise modify
{
Deleetting. settings [Key]. value = value;
}
Config. Save (configurationsavemode. Full );
}
2. Configure node Encryption
Sometimes we need to encrypt key nodes, and. NET provides us with an encryption method. The following shows how to encrypt connectionstrings nodes:
Public static void protectsection ()
{
Configuration Config = webconfigurationmanager. openwebconfiguration ("~ ");
Configurationsection section = config. Sections ["connectionstrings"];
Section. sectioninformation. protectsection ("rsaprotectedconfigurationprovider ");
Section. sectioninformation. forcesave = true;
Config. Save (configurationsavemode. Full );
}
Here we use rsaprotectedconfigurationprovider. After encryption, The connectionstrings node is:
<Connectionstrings configprotectionprovider = "rsaprotectedconfigurationprovider">
<Encrypteddata type = "http://www.w3.org/2001/04/xmlenc#Element"
Xmlns = "http://www.w3.org/2001/04/xmlenc#">
<Encryptionmethod algorithm = "http://www.w3.org/2001/04/xmlenc#tripledes-cbc"/>
<Keyinfo xmlns = "http://www.w3.org/2000/09/xmldsig#">
<Encryptedkey xmlns = "http://www.w3.org/2001/04/xmlenc#">
<Encryptionmethod algorithm = "http://www.w3.org/2001/04/xmlenc#rsa-1_5"/>
<Keyinfo xmlns = "http://www.w3.org/2000/09/xmldsig#">
<Keyname> RSA key </keyname>
</Keyinfo>
<Cipherdata>
<Ciphervalue> sg75nxctusmjwzg9ypluzh9cese6qa1aphxlpz + signature + Signature = </ciphervalue>
</Cipherdata>
</Encryptedkey>
</Keyinfo>
<Cipherdata>
<Ciphervalue> encrypt + nzijqct + q + odxpweprsi/f1tg/weight + qcvibhwtc + weight + csjij 4Cm + weight/weight + weight/ifa1q16ns + weight + ji1 + weight + ru2xh4k84axbmgcla5vuazb </ciphervalue>
</Cipherdata>
</Encrypteddata>
</Connectionstrings>
You can view the demo instance for all the above operations.
Download demo