. NET Website Web. config configuration instructions

Source: Internet
Author: User
Tags configuration settings error status code http cookie

1. Understand the Web. config file

The Web. config file is an XML text file used to store ASP. NET web applications.ProgramConfiguration information (for example, the most common setting of ASP. NET web application authentication method), it can appear in every directory of the application. When you pass. after creating a web application, a default web application is automatically created in the root directory by default. config file, including the default configuration settings. All subdirectories inherit its configuration settings. If you want to modify the configuration settings of a subdirectory, you can create a web. config file under the subdirectory. It can provide configuration information other than the configuration information inherited from the parent directory, or rewrite or modify the settings defined in the parent directory.

(1). Web. config is stored in XML format. configuration files are classified into the following formats:

1. Configuration section handler Declaration

Feature: it is located at the top of the configuration file and included in the <configsections> flag.

2. Specific Application configuration

Feature: It is located in <deleetting>. You can define global constant settings and other information of an application.

3. Configuration section settings

Features: In the <system. Web> section, you can control Asp.net runtime behaviors.

4. Configure the section group

Feature: You can use the <sectiongroup> label to customize the group, which can be placed inside <configsections> or other <sectiongroup> labels.

(2). Configuration section

1. <configuration> section

Root element, and other sections are inside it.

2. <deleetting> section

This section defines application settings. You can also set some uncertain settings based on your actual situation.




<Add key = "conntction" value = "Server =; userid = sa; Password =; database = Info;"/>


Defines a connection string constant, and can modify the connection string in the actual application, without modifying the programCode.

Ii. <deleetask>

<Add key = "errpage" value = "error. aspx"/>


Defines an error redirect page.

3. <compilation> section



Defaultlanguage = "C #"

DEBUG = "true"


I. default language: defines the background code language. You can select C # And VB.net.

When iidebug is set to true, aspx debugging is started; if it is set to false, aspx debugging is not started, so the application program can be improved.

Performance. Generally, programmers are set to true during development and false when handed over to customers.

4. <customerrors> section



Mode = "remoteonly"

Defaultredirect = "error. aspx"

<Error statuscode = "440" Redirect = "err0000page. aspx"/>

<Error statuscode = "500" Redirect = "err500page. aspx"/>


I. Mode: it has three states: On, off, And remoteonly. On indicates that custom information is always displayed; Off indicates that detailed Asp.net error information is always displayed; remoteonly indicates that custom information is only displayed for users not running on the Local Web server.

Ii. defaultredirect: the URL used for redirection when an error occurs. Optional.

Iii. statuscode: indicates the error status code, indicating a specific error status.

Iv. Redirect: the URL of the error redirection.

5. <globalization> section



Requestencoding = "UTF-8"

Responseencoding = "UTF-8"

Fileencoding = "UTF-8"


I. requestencoding: used to check the encoding of each request.

Ii. responseencoding: used to check the encoding of the returned response content.

Iii. fileencoding: used to check the default encoding for parsing files such as aspx and asax.

6. <sessionstate> section



Mode = "inproc"

Stateconnectionstring = "TCPIP = 42424"

Sqlconnectionstring = "Data Source =; trusted_connection = yes"

Cookieless = "false"

Timeout = "20"


I. Mode: status options include off, inproc, StateServer, and sqlserver.

This property is detailed here: http://blog.csdn.net/chengking/archive/2005/10/27/518079.aspx

Ii. stateconnectionstring: Specifies the name of the server in which the Asp.net application stores the remote session status. The default value is local.

Iii. sqlconnectionstring: When a database in session status is used, set the connection string here.

Iv. cookieless: if it is set to true, the cookie session status is not used to identify the customer. Otherwise, the opposite is true.

V. Timeout: used to define the time for storing session status. If the duration is exceeded, the session is automatically terminated.

7. <authentication> section


<Authentication mode = "forms">

<Forms name = ". aspxuserdemo" loginurl = "login. aspx" Protection = "all" timeout = "30"/>



<Deny users = "? "/>


I. Windows: using IIS Authentication

Ii. Forms: use form-based authentication

Iii. Passport: Passport cookie Authentication Mode

Iv. None: no verification method is used.

Meaning of the attributes of embedded forms nodes:

I. Name: Specifies the name of the HTTP cookie that completes authentication.

Ii. loginurl

Iii. Protection: Specifies the cookie data protection method.

It can be set to: All none encryption validation.

A. All indicates data encryption and verification of validity.

B. None indicates that the cookie is not protected.

C. Encryption indicates encryption of cookie content

D. Validation indicates that the cookie content is validated.

Iv. Timeout: Specifies the cookie expiration time. After timeout, you must log on again.

Modifications to the Web. config file at runtime can take effect without restarting the Service (note: the exception in <processmodel> section ). Of course, the Web. config file can be expanded. You can customize new configuration parameters and write the configuration section handler to process them.

All the following codes in the web. config configuration file (default configuration settings) should be


<System. Web>


</System. Web>


For the purpose of learning, the following examples omit this XML tag.

1. <authentication> section

Purpose: Configure ASP. NET authentication support (Windows, forms, passport, none ). This element can only be declared at the computer, site, or application level. The <authentication> element must be used with the <authorization> section.


In the following example, the website is configured for form-based authentication. When a user who does not log on to the website that requires authentication, the webpage automatically jumps to the logon webpage.

<Authentication mode = "forms">

<Forms loginurl = "Logon. aspx" name = ". formsauthcookie"/>


The element loginurl indicates the name of the login webpage, and name indicates the cookie name.

2. <authorization> section

Purpose: control access to URL resources from clients (for example, Anonymous Users are allowed ). This element can be declared at any level (computer, site, application, subdirectory or page. Must be used with the <authentication> section.

Example: The following example disables access by anonymous users:


<Deny users = "? "/>


Note: You can use user. identity. to obtain the authenticated user name. You can use the web. security. formsauthentication. the redirectfromloginpage method redirects authenticated users to the page the user just requested. specific

3. <compilation> section

Purpose: configure all compilation settings used by ASP. NET. The default debug attribute is "true". After the program is compiled and delivered, set it to false (the web. config file is described in detail, and the example is omitted here)

4. <customerrors>

Purpose: Provide information about custom Errors for ASP. NET applications. It is not applicable to errors in XML Web Services.

Example: When an error occurs, redirect the webpage to the custom error page.

<Customerrors defaultredirect = "errorpage. aspx" mode = "remoteonly">


The defaultredirect element indicates the name of the custom error webpage. Mode element: displays custom (friendly) information for users not running on the Local Web server.


Purpose: Configure ASP. net http Runtime Library settings. This section can be declared at the computer, site, application, and subdirectory level.

For example, the maximum size of a file to be uploaded is 4 MB, the maximum time is 60 seconds, and the maximum number of requests is 100.

<Httpruntime maxrequestlength = "4096" executiontimeout = "60" apprequestqueuelimit = "100"/>

6. <pages>

Purpose: Identify page-specific configuration settings (such as whether to enable session Status, view status, and whether to detect user input ). <Pages> statements can be made at the computer, site, application, and subdirectory level.

Example: do not check whether there is potential dangerous data in the content entered by the browser (Note: This item is checked by default. If you do not check, 1. encode or verify user input). When you send a page from the client, the encrypted view status is checked to verify that the view status has been tampered with on the client. (Note: This item is not verified by default)

<Pages buffer = "true" enableviewstatemac = "true" validaterequest = "false"/>

7. <sessionstate>

Purpose: Configure session Status settings for the current application (for example, whether to enable session Status and the location where session status is saved ).


<Sessionstate mode = "inproc" cookieless = "true" timeout = "20"/>



Mode = "inproc" indicates that the session status is stored locally (you can also choose to store the session status on a remote server or Sal server or not enable the session status)

Cookieless = "true" indicates that session status is enabled if the user's browser does not support cookies (the default value is false)

Timeout = "20" indicates the number of minutes in which the session can be idle.

8. <trace>

Purpose: configure the ASP. NET tracking service, which is mainly used for program testing to identify errors.

Example: The default configuration in Web. config is as follows:

<Trace enabled = "false" requestlimit = "10" pageoutput = "false" tracemode = "sortbytime" localonly = "true"/>


Enabled = "false" indicates that tracing is not enabled;

Requestlimit = "10" indicates the number of Trace Requests stored on the server.

Pageoutput = "false" indicates that the trace output can only be accessed through the tracking utility;

Tracemode = "sortbytime" indicates that trace information is displayed in the order of processing traces.

Localonly = "true" indicates that the trace Viewer (trace. axd) is used only for the host web server.

Custom web. config file configuration

The configuration section of the custom web. config file consists of two steps.

1. Declare the name of the configuration section and the name of the. NET Framework class that processes the configuration data in the section between the <configsections> and </configsections> labels at the top of the configuration file.

2. Configure the declared section after the <configsections> area.

Example: Create a storage database connection string



<Section name = "etetction" type =" system. configuration. namevaluefilesectionhandler, system, version = 1.0.3300.0, culture = neutral, publickeytoken = b77a5c561934e089 "/>



<Add key = "scon" value = "Server = A; database = northwind; uid = sa; Pwd = 123"/>


<System. Web>


</System. Web>


To access the Web. config file, you can use the configurationsettings. deleettings static string set to access the Web. config file example: Obtain the connection string created in the preceding example. For example:

Protected static string isdebug = configurationsettings. deleettings ["debug"]

Ii. Explanation of session configuration in Web. config

After opening the configuration file web. config of an application, we will find the following section:


Mode = "inproc"

Stateconnectionstring = "TCPIP = 42424"

Sqlconnectionstring = "Data Source =; trusted_connection = yes"

Cookieless = "false"

Timeout = "20"


This section describes how the application stores session information. The following operations mainly aim at this configuration section. Let's take a look at the meaning of the content contained in this section. The syntax of the sessionstate node is as follows:

<Sessionstate mode = "off | inproc | StateServer | sqlserver"

Cookieless = "True | false"

Timeout = "number of minutes"

Stateconnectionstring = "TCPIP = server: Port"

Sqlconnectionstring = "SQL connection string"

Statenetworktimeout = "number of seconds"


The required attribute is the description of the attribute option.

Mode setting: Where to store session information

Set off to not use the session function,

Ø inproc is set to store sessions in the process, which is the storage method in ASP. This is the default value,

Ø StateServer is set to store sessions in independent State services,

SQL Server stores sessions in SQL Server.

Optional properties: description of the property options

Ø cookieless sets where the session information of the client is stored,

Ø ture uses cookieless mode,

Ø false uses cookie mode. This is the default value,

The timeout parameter specifies the number of minutes after which the server automatically waives the session information. The default value is 20 minutes.

Stateconnectionstring is the name and port number of the server used to store session information in the status service, for example, "TCPIP = 42424 ". This attribute is required when the mode value is StateServer.

Sqlconnectionstring sets the connection string when connecting to SQL Server. For example, "Data Source = localhost; Integrated Security = sspi; initial catalog = northwind ". This attribute is required when the mode value is sqlserver.

Statenetworktimeout sets the number of seconds after the session state is stored in StateServer mode and the TCP/IP connection between the Web server and the server that stores the status information. The default value is 10 seconds.

Storage of client session Status in ASP. NET

In our previous session model introduction, we can find that the session status should be stored in two places: client and server. The client is only responsible for saving the sessionid of the corresponding website, while other session information is stored on the server. In ASP, the sessionid of the client is actually stored as a cookie. If the user chooses to disable cookies in the browser settings, then he will not be able to enjoy the convenience of the session, or even access some websites. To solve the above problems, the session information storage methods of the client in ASP. NET are divided into cookie and cookieless.

In ASP. NET, by default, session information is stored on the client using cookies. If you want to use cookieless on the client to store session information, the method is as follows:

Find the root directory of the current web application, open the Web. config file, and find the following section:


Mode = "inproc"

Stateconnectionstring = "TCPIP = 42424"

Sqlconnectionstring = "Data Source =; trusted_connection = yes"

Cookieless = "false"

Timeout = "20"


In this section, cookieless = "false" is changed to cookieless = "true". In this way, the session information of the client is no longer stored using cookies, but stored through URLs. Close the current IE, open a new IE, and re-access the Web application, you will see something similar to the following:

Http: // localhost/mytestapplication/(ulqsek45heu3ic2a5zgdl245)/default. aspx indicates the session ID of the client. Note that this information is automatically added by IIS and does not affect the normal connection.

ASP. NET Server session state storage preparation:

To better experience the experiment, you can create a page named sessionstate. aspx and add the following code to <body> </body>.

<Scriptrunat = "server">

Sub session_add (sender as object, e as eventargs)

Session ("mysession") = text1.value

Span1.innerhtml = "session data updated! <P> your session contains: <font color = Red> "& SESSION (" mysession "). tostring () &" </font>"

End sub

Sub checksession (sender as object, EAS eventargs)

If (Session ("mysession") is nothing) then

Span1.innerhtml = "nothing, session data lost! "


Span1.innerhtml = "your session contains: <font color = Red>" & SESSION ("mysession"). tostring () & "</font>"

End if

End sub


<Formrunat = "server" id = "form2">

<Inputid = "text1" type = "text" runat = "server" name = "text1">

<Inputtype = "Submit" runat = "server" onserverclick = "session_add"

Value = "add to session state" id = "submit1" name = "submit1">

<Inputtype = "Submit" runat = "server" onserverclick = "checksession"

Value = "View session state" id = "submit2" name = "submit2">


<Hrsize = "1">

<Fontsize = "6"> <spanid = "span1" runat = "server"/> </font>

This sessionstate. ASPX page can be used to test whether session information is lost on the current server.

Store Server session information in the process

Let's go back to the section in the web. config file:


Mode = "inproc"

Stateconnectionstring = "TCPIP = 42424"

Sqlconnectionstring = "Data Source =; trusted_connection = yes"

Cookieless = "false"

Timeout = "20"


When the mode value is inproc, it indicates that the server is using this mode.

This method is the same as the previous ASP mode, that is, the server stores session information in the IIS process. When IIS is disabled or restarted, the information is lost. However, this mode also has its own biggest advantage, that is, the highest performance. It should be that all session information is stored in the IIS process, so IIS can quickly access this information, the performance of this mode is much faster than that of session information stored outside the process or stored in SQL Server. This mode is also the default mode for ASP. NET.

Now let's do a test. Open the sessionstate. ASPX page and enter some characters to store them in the session. Then, let's restart IIS. Note that it is not to stop the current site and start again, but to right-click the node of the machine name in IIS and choose restart IIS. (To restart IIS when NT4 is used, you must restart the computer. Microsoft returns sessionstate. on the ASPX page, check the session information and find that the information has been lost.

Store Server session information outside the process

First, let's open the management tool> service, find the service named ASP. NET State service, and start it. In fact, this service is to start a process to save session information. After starting this service, you can see a process named aspnet_state.exe in the Windows Task Manager> process. This is the process for saving session information.

Return to the preceding section in the web. config file and change the mode Value to StateServer. Open another IE after saving the file, open the sessionstate. ASPX page, and save some information to the session. At this time, let's restart IIS and return to the sessionstate. ASPX page to view the session information.

In fact, this method of storing session information outside the process not only means that the information can be stored in the local process, but also the session information can be stored in other server processes. In this case, you not only need to change the mode Value to StateServer, but also need to configure the corresponding parameters in stateconnectionstring. For example, if you want to store the session in the process of a computer whose IP address is, you need to set it to stateconnectionstring = "TCPIP = 42424 ". Of course, do not forget to install. NET Framework on the computer and start the ASP. NET State Services Service.

Store Server session information in SQL Server

First, let's make some preparations. Start the SQL Server and SQL Server proxy services. Execute a script file named installsqlstate. SQL in SQL Server. This script file will create a database in SQL Server for storing session information and an SQL Server proxy job for maintaining the session information database. You can find the file in the following path:

[System Drive] \ winnt \ Microsoft. NET \ framework \ [version] \

Then open the query analyzer, connect to the SQL Server server, open the file and execute it. Wait a moment and the database and job will be created. In this case, you can open the Enterprise Manager and see a new database called aspstate. However, this database only contains some stored procedures and does not use user tables. In fact, session information is stored in the aspstatetempsessions table of the tempdb database, and the other aspstatetempapplications table stores the Application Object Information in ASP. These two tables are also created by the script just now. In addition, you can view "manage"> "SQL Server proxy"> "job" and find another job called aspstate_job_deleteexpiredsessions. This job actually deletes expired session information from the aspstatetempsessions table every minute.

Then, we return to the Web. config file and change the mode Value to sqlserver. Note: You must also modify the sqlconnectionstring value in the following format:

Sqlconnectionstring = "Data Source = localhost; Integrated Security = sspi ;"

Data source refers to the IP address of the SQL Server server. If SQL Server and IIS are a server, write Integrated Security = sspi means to use Windows Integrated Identity Authentication, so that accessing the database will use ASP.. Net identity, through this configuration, you can obtain better security than the SQL Server authentication method using userid = sa; Password = password. Of course, if SQL server runs on another computer, you may need to maintain consistency between the two sides through Active Directory domains.

let's do a test. Add the session information to sessionstate. aspx and you will find that the session information already exists in SQL Server. Even if you restart the computer, the session information will not be lost. Now, you have fully seen what session information looks like and what it is stored in SQL Server. What you can do depends on your performance.

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.