1. Understand the Web. config file
Web. config is an XML text file used to store ASP. NET Web application configuration information (for example, the most common settings ASP. NET Web application authentication method), which 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.
Usage:
I.
<Deleetask>
<Add key = "Conntction" value = "server = 192.168.85.66; userid = sa; password =; database = Info;"/>
<Deleetask>
A connection string constant is defined, and the connection string can be modified in actual application without modifying the program code.
II. <deleetask>
<Add key = "ErrPage" value = "Error. aspx"/>
<Deleetask>
Defines an error redirect page.
3. <compilation> section
Format:
<Compilation
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
Format:
<CustomErrors
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
Format:
<Globalization
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
Format:
<SessionState
Mode = "InProc"
StateConnectionString = "tcpip = 127.0.0.1: 42424"
SqlConnectionString = "data source = 127.0.0.1; 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
Format:
<Authentication mode = "Forms">
<Forms name = ". ASPXUSERDEMO" loginUrl = "Login. aspx" protection = "All" timeout = "30"/>
</Authentication>
<Authorization>
<Deny users = "? "/>
</Authorization>
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
<Configuration>
<System. web>
And
</System. web>
</Configuration>
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.
Example:
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"/>
</Authentication>
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:
<Authorization>
<Deny users = "? "/>
</Authorization>
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">
</CustomErrors>
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.
5.
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 ).
Example:
<SessionState mode = "InProc" cookieless = "true" timeout = "20"/>
</SessionState>
Note:
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"/>
Note:
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
<Configuration>
<ConfigSections>
<Section name = "etetction" type =" System. Configuration. NameValueFileSectionHandler, System, Version = 1.0.3300.0, Culture = neutral, PublicKeyToken = b77a5c561934e089 "/>
</ConfigSections>
<Deleetask>
<Add key = "scon" value = "server = a; database = northwind; uid = sa; pwd = 123"/>
</AppSettings>
<System. web>
......
</System. web>
</Configuration>
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:
<SessionState
Mode = "InProc"
StateConnectionString = "tcpip = 127.0.0.1: 42424"
SqlConnectionString = "data source = 127.0.0.1; 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 = 127.0.0.1: 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:
<SessionState
Mode = "InProc"
StateConnectionString = "tcpip = 127.0.0.1: 42424"
SqlConnectionString = "data source = 127.0.0.1; 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! "
Else
Span1.InnerHtml = "Your session contains: <font color = red>" & Session ("MySession"). ToString () & "</font>"
End If
End Sub
</Script>
<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">
</Form>
<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:
<SessionState
Mode = "InProc"
StateConnectionString = "tcpip = 127.0.0.1: 42424"
SqlConnectionString = "data source = 127.0.0.1; 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 192.168.0.2, you need to set it to stateConnectionString = "tcpip = 192.168.0.2: 42424 ". Of course, do not forget to install. NET Framework on the computer 192.168.0.2 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] winntMicrosoft. NETFramework [version]
Then open the query analyzer, connect to the SQL 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. If SQL Server and IIS are a Server, write 127.0.0.1. 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.