Web. config configuration in ASP.

Source: Internet
Author: User
Tags connectionstrings

Web. config configuration in directory ASP. 11. configuration File Save location ... 22. configuration file Loading order ... 23. Configuration File Node Introduction ... 31. . 32.. 53. . 54. . 6 . 114, for the configuration file of some programming operations ... 111. Configuration file modification at runtime ... 112. Configure the encryption of the node ... 12web.config is an important file for storing 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. NET's default profile 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. CLIP_IMAGE001[1] Figure: The directory in which Web. config is located has two very important configuration files, 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 load order when IIS starts the ASP, the configuration information in the configuration file is loaded, and the information is cached, not every time it is used to read the configuration file, but IIS is monitoring the changes of these files at any time, and it will re-read and cache the configuration information. When the ASP. NET site runs, the node information in the configuration file is loaded as follows: 1) If there is a Web. config file in the same directory as the current 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 Web. config or required configuration nodes do not exist in the site root, go to the "Windows directory \microsoft.net\framework\ corresponding. 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) the virtual directory in IIS6 is not the root directory. 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. III. Profile Node Introduction the Web. config file is an XML text file whose root node is , which contains common child nodes under the node: 、、 (Save database connection string), And 。 The following are described for each node configuration. 1. 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: 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 a sample to write a custom configuration information and complete its sectionhandler, first we Add configsections under the node. 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 + "
");}} 2. 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. The call method is: string imgtype = configurationmanager.appsettings["Imgtype"];3. ConnectionStrings and appsettings are similar, but for saving configuration database connection information, here is an instance. Called as: string connstr = configurationmanager.connectionstrings["Sqlserverconnstr"]. Connectionstring;4. Configure 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 of the important configuration nodes. 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. This node configures the ASP. NET authentication scheme, which is used to identify the users who view the ASP. The Mode property contains 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 designates ASP. Forms-based authentication as the default authentication mode. 3. Passport specifies Microsoft Passport Network authentication as the default authentication mode. 4. None does not specify any authentication. 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. Login.aspx in the login through: 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: Write Abchttphandler:namespace Configtest.httphandler{public class Abchttphandler:ihttphandler, IRequiresSessionState{ public bool Isreusable{get {return true;}} public void ProcessRequest (HttpContext context) {context. Response.Write (" Hello HttpHandler"); context. session["Test"] = "You call the session in the Abchttphandler container"; Response.Write (context. session["Test"]);}}} System call Result: Clip_image002[1] Figure: HttpHandler Test We can also use Httphandlerfactory to do handler self-switching. We first define two HttpHandler, namely HttpHandler1 and HttpHandler2. Then define a myhandlerfactory that inherits from IHttpHandlerFactory to dynamically switch HttpHandler, see 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 Handlerreturn 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 ("HttpHandler1");}} public class Httphandler2:ihttphandler, Irequiressessionstate{public bool Isreusable{get {return true;}} public void ProcessRequest (HttpContext context) {context. Response.Write ("HttpHandler2");}}} 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: Added a HttpHandler configuration item for all files under Handlerfactory directory, we run test: clip_image004[1] 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. As with HttpHandler, write Httpmodule:namespace Configtest.httpmodule{public class myhttpmodule:ihttpmodule{that inherits from 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! See results: clip_image006[1] Figure: HttpModule test 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. To add a watermark to a picture of a specified directory: Iv. some programming operations for profiles 1. Configuration file modification at runtime here we demonstrate modifications to the appsettings node: public static void Setappsetting (string key, String value) {Configuration Config = Webconfigurationmanager.openwebconfiguration ("~"); Appsettingssection appsetting = config. appsettings;//If it does not exist add if (appsetting.settings[key] = = null) {APPSETTING.SETTINGS.ADD (key, value);} else//otherwise modify {Appsetting.settings[key]. value = value;} Config. Save (configurationsavemode.full);} 2. Configuring node encryption Sometimes we have to 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"); Sectioninformation.forcesave = True;config. Save (configurationsavemode.full);} Here we are using RsaProtectedConfigurationProvider, after the connectionstrings node is encrypted: Rsa Key sg75nxctusmjwzg9ypluzh9cese6qa1aphxlpz+ emnwh4la9aheevbzxagbwvjpgejoqfonxpkhjenvzutrpm9t6djmu2vq6epmxmmf7lkng62nq1lok+ gktbjt8z3vsprazfteqawibhl8gwb4m94ko7bx6p5ifu6xgxpydoeq= zf47wegbte8wdp7pj8104ip1r0uuqndyiyfppan5e5tmtzihjqzzyngw+nzijqct+q+odxpweprsi/f1tg/ urixypfnhwjz7o0xps1lopqgg8y2mpq0j3jvozm8enjx3jl5ylzpquk7tsafyuyiht1ljjl2t+ Wwcqfqnvflfsxqkqvwde0wmveqjnsh09rpwjo4o2h9q9t6adafdz1wuzbr6edrudrxsizi8hxdwuu7bd4z2wdqao6vsuqk0kmep4zagzokbuleja800fv0otd h2fagvhfxqxxl5ejqsvcjjz7yviyjsjlj5rmb1lxjdbq0msrzqdelmnfvz2jubmwv7pkvk+qcvibhwtc+o0u4cgqlomsbmuwwzyqierxwymir+ csjij4cm+c6joleglszskafrrfe8qjjkixsivigvtha8s58vvfkphzo7znm91b+8bucaanl8kabktsobuddhfck/ j97gkyz5blheaxnpat47cj59p1sqqqogm0ghujyns4jtgs9jodb4gbocpivmbtzg4mhlwgenshleuu5x9sqnckyoguk14wo9vb4++ jirxcysdmkucgqqxlwtz0fy/ifa1q16ns+l5mbfyvaol8hbrhbgwgaodhhsj3ushlp+ji1+ Buegxc8o1r0hpnquifxqhvgd2rkdqyhcgohydlpayldl0epjgytoaer530s89t52+ru2xh4k84axbmgcla5vuazb All of the above can be seen in the demo instance.

Web. config configuration in ASP.

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.