1. Understand the Web. config file
The Web. config file is an XML text file used to store ASP. NET web applications. Program Configuration 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.
Usage:
I.
<Deleetask>
<Add key = "conntction" value = "Server = 192.168.85.66; userid = sa; Password =; database = Info;"/>
<Deleetask>
Defines a connection string constant, and can modify the connection string in the 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.
II Debug : When it is true, start aspx debugging; if it is false, the application program can be improved because aspx debugging is not started.
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 : 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.
(See the next article: ASP. NET performance optimization)
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 : 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
? Nbsp; off is set to not use the session function,
? Nbsp; inproc is set to store the session in the process, which is the storage method in ASP. This is the default value,
? Nbsp; StateServer is set to store sessions in independent State services,
? Nbsp; sqlserver settings store sessions in SQL Server.
the optional attribute is: Description of the attribute option
? Nbsp; cookieless sets where the session information of the client is stored.
? Nbsp; ture uses cookieless mode.
? Nbsp; false uses cookie mode. This is the default value.
? Nbsp; timeout indicates the number of minutes after which the server automatically abandons the session information. The default value is 20 minutes.
stateconnectionstring indicates the server name and port number 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 Web. in the section in the config file:
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, this 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] \ 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 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.
Similarly, 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.
Summary
Pass this articleArticleIn terms of session management and maintenance, ASP. NET has made great progress over ASP. we can select the appropriate methods at will. For enterprise applications, this is undoubtedly beneficial to server synchronization, server stability, and reliability. I believe that with the support of powerful Microsoft, the new generation of e-commerce platforms will be built better!
At the same time, you will also find that the entire technology includes the integration of operating systems, Web Services, and database technologies. I believe that windows is not UNIX stable, IIS is not apache stable, and SQL server is not powerful as Oracle. But who can perfectly link them together? So, although Microsoft is not too strong in every aspect, if Microsoft's things are integrated together, who would say that it is not powerful? Microsoft is Microsoft!
Iii. Asp.net general settings on form Authentication
Asp.net general settings on form authentication:
1: Add form authentication in Web. config;
<Authentication mode = "forms">
<Forms name = "auth" loginurl = "index. aspx" timeout = "30"> </Forms>
</Authentication>
<Authorization>
<Deny users = "? "/>
</Authorization>
2: If a registration page exists, anonymous users should also be allowed to call the registration page for registration;
The following code should be between <configuration> <system. Web> and not between <system. Web>... </system. Web>;
---------------- Indicates that anonymous users are allowed to access the userreg. ASPX page.
<Location Path = "userreg. aspx">
<System. Web>
<Authorization>
<Allow users = "? "/>
</Authorization>
</System. Web>
</Location>
3. After Successful Logon, you must create an authentication ticket to indicate that the authenticated user has been valid;
If (LOGIN successful)
System. Web. Security. formsauthentication. setauthcookie (user name, false );
4. 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 ["scon"]
This article is transferred from doorle's blog-dulle blog: http://www.doorle.cn/blog/article.asp? Id = 923