Web. config configuration (reprint)

Source: Internet
Author: User
Tags connectionstrings

Web. config configuration in ASP.

by Bendon 20101123

Directory

Web. config configuration in ASP. 1

One, the configuration file save location ... 2

Second, the configuration file loading order ... 2

Iii. Configuration file Node Introduction ... 3

1. <configsections>. 3

2. <appsettings>. 5

3. <connectionstrings>. 5

4. <system.web>. 6

<location>. 11

Iv. Some programming actions for configuration files ... 11

1. configuration file modification at runtime ... 11

2. Configure the encryption of the node ... 12

Web. config is an important file for saving configuration information, such as database connection strings, in ASP. It is an XML-based text file that is placed in any directory of the Web application and is not compiled into a DLL with the source file by default, and the runtime monitors it for changes, but the system automatically reloads the latest content when it changes.

One, the configuration file save location

The default profile for. NET is saved under the Windows directory \microsoft.net\framework\ corresponding. NET version \config folder. Different operating system Windows directories are not the same, we enter "Echo%windir%" at the command line to see where the Windows directory is located.

Figure: directory where Web. config resides

There are two very important configuration files in ASP. Machine.config and Web. config, which are located under the Config folder. These two files generally do not need us to maintain it manually, keep it by default. However, for an ASP. NET application, it will have 0, 1 or more web. config profiles on its own, with multiple configuration files having a load order problem. The following section describes.

Note that the legendary. net3.0 and. net3.5 are only expanded on the basis of. Net2.0, so it's useless. net2.0 configuration file. They don't even have the config directory.

Second, the configuration file loading order

When IIS starts the ASP, the configuration information in the configuration file is loaded, and the information is cached, not each time it is used to read the configuration file, but IIS monitors the changes of these files at any time, and it will re-read and cache the configuration information.

The ASP. NET site Runtime loads the node information in the configuration file as follows:

1) If there is a Web. config file in the same directory as the currently running page, find out if the required node exists, return the result if it exists, and stop looking for the next step.

2) If the directory does not exist in the Web. config configuration or the configuration file does not have the required nodes, look for the node in the configuration file of the top level directory where it resides, until the site root directory. (Problem: Virtual directories in IIS6 are not root directories)

3) If the Web. config or desired configuration node does not exist in the root directory of the site, go to "Windows directory \microsoft.net\framework\. NET version \CONFIG\Web.config" to find.

4) If not found in 3rd, continue to the "Windows directory \microsoft.net\framework\ corresponds to. NET version \config\machine.config" to find.

5) If you have not found it, then error it.

There are two questions

1) virtual directories in IIS6 are not considered root directories.

2) When the system is running, manually add a Web. config in a directory that does not already have Web. config and will not load automatically.

Introduction of configuration file node

The Web. config file is an XML text file whose root node is <configuration>, and that node contains common child nodes with:<configsections>, <appSettings>, <connectionStrings> (Save database connection string), <location>, and <system.web>. The following are described for each node configuration.

1. <configSections>

The configsections element specifies the configuration section and the handler declaration. Because ASP. NET does not make any assumptions about how to handle the settings within the configuration file, this is necessary. However, ASP. NET will delegate processing of configuration data to the configuration section handler. The configuration structure information is as follows:

<configSections>

<!--defines the association between a configuration section handler and a configuration element. -

<section/>

<!--defines the association between a configuration section handler and a configuration section. -

<sectiongroup/>

<!--Remove references to inherited sections and section groups. -

<remove/>

<!--remove all references to inherited sections and section groups, allowing only the sections and section groups that are added by the current section and sectiongroup elements. -

<clear/>

</configSections>

Each section element identifies a configuration stanza or element and the associated ConfigurationSection derived class that is processed for that configuration section or element. You can logically group the section elements in the sectiongroup element to organize the section elements and avoid naming conflicts. The section and sectiongroup elements are included in the configsections element.

If the configuration file contains a configsections element, the configsections element must be the first child element of the configuration element.

Let's take the example to write a custom configuration information and complete its sectionhandler, first we 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>

To write a custom Sectionhandler, we return a hashtable of 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;

}

}

}

The section is used in the page, and the Hashtable returned by the Configurationmanager.getsection is obtained by the Sectionhandler. Note 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. <appSettings>

This node is primarily used to store some configuration information for an ASP. NET application, but also to put the database connection string here, but. net2.0 provides the connectionstrings node, so the database connection string is still not recommended here, the following is an instance of a picture type.

<appSettings>

<!--picture type extension--

<add key= "Imgtype" value= ". bmp;. JPG;. GIF;. PNG "/>

</appSettings>

The Calling method is:

String imgtype = configurationmanager.appsettings["Imgtype"];

3. <connectionStrings>

ConnectionStrings and appsettings are similar, but for saving configuration database connection information, here 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 method is called:

String connstr = configurationmanager.connectionstrings["Sqlserverconnstr"]. ConnectionString;

4. <system.web>

<system.web> configures a node for the behavior of a. NET application that contains many child nodes, many of which are already configured with. NET, and here we only look at some important configuration nodes.

Ø<customerrors>

<customerrors defaultredirect= "genericerror.htm" mode= "RemoteOnly" >

<error statuscode= "$" redirect= "internalerror.htm"/>

</customErrors>

Where the mode attribute has three values, on/off/remoteonly, the default is RemoteOnly. The error node specifies a custom error page for the given HTTP status code.

Ø<authentication>

This node configures the ASP. NET authentication scheme, which is used to identify the users who view the ASP. The Mode property consists of four authentication modes:

1. Windows (default)

Specifies Windows authentication as the default authentication mode. Use it together with any of the following forms of Microsoft Internet Information Services (IIS) authentication: Basic, Digest, Integrated Windows authentication (Ntlm/kerberos), or certificate. In this case, your application delegates the authentication responsibility to the underlying IIS.

2. Forms

Specify ASP. Forms-based authentication as the default authentication mode.

3. Passport

Specifies Microsoft Passport Network authentication as 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 forms-based authentication, specify the name of a Cookie that transmits logon information from the client, and specify the name of the login page to use when initial authentication fails. The authorization section must be included in order to require Forms authentication for all users and to deny anonymous users access to the site.

<configuration>

<system.web>

<authentication mode= "Forms" >

<forms name= "401kApp" loginurl= "/login.aspx"/>

</authentication>

<authorization>

<deny users= "?" />

</authorization>

</system.web>

</configuration>

Login.aspx in the landing by:

FormsAuthentication.RedirectFromLoginPage (this. TextBox1.Text, True);

Ø

The httphandlers can be used to map incoming requests to the appropriate handlers based on the URLs and HTTP verbs specified in the request. Special processing can be done for special files specified under a specific directory.

Let's write a custom httphandle for all *.ABC folders under the path directory of the Web site.

Add to configuration file first:

<add path= "PATH/*.ABC" verb= "*" type= "Configtest.httphandler.abchttphandler,configtest.httphandler"/>

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 the 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 by itself. We first define two HttpHandler, namely HttpHandler1 and HttpHandler2. Then define a myhandlerfactory that inherits from IHttpHandlerFactory to dynamically switch HttpHandler, looking at 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 ();

}

Returns the default handler

Return to 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 the test, we set the URL in the presence of 1 this character with HttpHandler1, there is 2 the word character with HttpHandler2, otherwise return the system default handler. We also have to add the configuration:

<add path= "PATH/*.ABC" verb= "*" type= "Configtest.httphandler.abchttphandler,configtest.httphandler"/>

<add path= "Handlerfactory/*.*" verb= "*" type= "Configtest.httphandler.myhandlerfactory,configtest.httphandler"/ >

Add a HttpHandler configuration item for all files in the Handlerfactory directory, we run the test:

Figure: Handlerfactory Test

Ø

When a request is passed in a pipeline, a series of events in the Httpapplicaion object are triggered. We have seen these events being published as events in Global.asax. This approach is application-specific, It 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 one entry in Web. config is required.

<add name= "Myhttpmodule" type= "Configtest.httpmodule.myhttpmodule,configtest.httpmodule"/>

As with HttpHandler, write a httpmodule that inherits 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 a sentence on each page: add beginrequest by myhttpmodule! look at the result:

Figure: HttpModule Test

<location>

The location node is the resource used to specify the child configuration. If you want to do special processing of a directory in an ASP. NET application, you can do so with that node. Give two examples.

The following code example demonstrates how to set the upload file size limit for a specified page to only KB.

<configuration>

<location path= "Uploadpage.aspx" >

</location>

</configuration>

To add a watermark to a picture of a specified directory:

<configuration>

<location path= "Images" >

<system.web>

<add verb= "*" path= "*.jpg" type= "ImageHandler"/><!--picture watermark Settings handler-->

</system.web>

</location>

</configuration>

Iv. some programming operations for profiles 1. Changes to configuration files at run time

Here we demonstrate the modification of the appsettings node:

public static void Setappsetting (string key, String value)

{

Configuration config = webconfigurationmanager.openwebconfiguration ("~");

Appsettingssection appsetting = config. AppSettings;

Add if it does not exist

if (appsetting.settings[key] = = null)

{

APPSETTING.SETTINGS.ADD (key, value);

}

else//otherwise modified

{

Appsetting.settings[key]. Value = value;

}

Config. Save (Configurationsavemode.full);

}

2. Configuring encryption for nodes

Sometimes we encrypt the key nodes, and. NET provides us with an encryption method, which we demonstrate to encrypt the connectionstrings node:

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 are using RsaProtectedConfigurationProvider, after the connectionstrings node is encrypted:

<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+ emnwh4la9aheevbzxagbwvjpgejoqfonxpkhjenvzutrpm9t6djmu2vq6epmxmmf7lkng62nq1lok+ Gktbjt8z3vsprazfteqawibhl8gwb4m94ko7bx6p5ifu6xgxpydoeq=</ciphervalue>

</CipherData>

</EncryptedKey>

</KeyInfo>

<CipherData>

<ciphervalue>zf47wegbte8wdp7pj8104ip1r0uuqndyiyfppan5e5tmtzihjqzzyngw+nzijqct+q+odxpweprsi/f1tg/ urixypfnhwjz7o0xps1lopqgg8y2mpq0j3jvozm8enjx3jl5ylzpquk7tsafyuyiht1ljjl2t+ Wwcqfqnvflfsxqkqvwde0wmveqjnsh09rpwjo4o2h9q9t6adafdz1wuzbr6edrudrxsizi8hxdwuu7bd4z2wdqao6vsuqk0kmep4zagzokbuleja800fv0otd h2fagvhfxqxxl5ejqsvcjjz7yviyjsjlj5rmb1lxjdbq0msrzqdelmnfvz2jubmwv7pkvk+qcvibhwtc+o0u4cgqlomsbmuwwzyqierxwymir+ csjij4cm+c6joleglszskafrrfe8qjjkixsivigvtha8s58vvfkphzo7znm91b+8bucaanl8kabktsobuddhfck/ j97gkyz5blheaxnpat47cj59p1sqqqogm0ghujyns4jtgs9jodb4gbocpivmbtzg4mhlwgenshleuu5x9sqnckyoguk14wo9vb4++ jirxcysdmkucgqqxlwtz0fy/ifa1q16ns+l5mbfyvaol8hbrhbgwgaodhhsj3ushlp+ji1+ Buegxc8o1r0hpnquifxqhvgd2rkdqyhcgohydlpayldl0epjgytoaer530s89t52+ru2xh4k84axbmgcla5vuazb</ciphervalue>

</CipherData>

</EncryptedData>

</connectionStrings>

All of the above can be seen in the demo instance.

Transfer from http://www.cnblogs.com/killme/archive/2010/11/23/1885587.html

Web. config configuration (reprint)

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.