I. Understanding of Web.config Documents
The Web.config file is an XML text file that stores configuration information for ASP.net Web applications (such as the most common settings asp.net the way the Web application is authenticated) and can appear in every directory in the application. When you pass. NET when you create a new Web application, by default, a default Web.config file is created automatically in the root directory, including the default configuration settings, and all subdirectories inherit its configuration settings. If you want to modify the configuration settings for subdirectories, you can create a new Web.config file in the subdirectory. It can provide configuration information in addition to the configuration information inherited from the parent directory, or you can override or modify the settings defined in the parent directory.
(i). Web.config are stored as XML file specifications, and the configuration files are grouped into the following formats
1. Configuration section Handler declaration
Features: Located at the top of the configuration file, included in the <configSections> logo.
2. Specific application configuration
Features: Located in <appSetting>. You can define information such as global constant settings for an application.
3. Configuration section Settings
Features: Located in <system. In the Web> section, you control the behavior of the ASP.net runtime.
4. Configuration section Group
Features: With <sectionGroup> tags, you can customize the grouping, can be placed inside <configSections> internal or other <sectionGroup> tags.
(ii). Each section of the configuration section
1.<configuration> section root element, the other section is inside of it.
2.<appsetting> section This section is used to define application settings items. For some uncertain settings, you can also allow users to set their own circumstances
Usage:
I.<appsettings>
<add key= "conntction" value= "server=192.168.85.66;userid=sa;password=;d atabase=info;" />
<appSettings>
A connection string constant is defined, and the connection string can be modified in practical application without modifying the code.
Ii.<appsettings>
<add key= "Errpage" value= "error.aspx"/><appsettings> defines an error redirection page.
3.<compilation> Festival
Format:
<compilation
Defaultlanguage= "C #"
Debug= "true"
/>
I.default language: Defines the background code language, which can be selected in C # and vb.net two languages.
Iidebug: When True, starts ASPX debugging, False does not start ASPX debugging, and thus improves the performance of the application while it is running. The normal program member is set to true at development time and is set to False when presented to the client.
4.<customerrors> Festival
Format:
<customerrors
Mode= "RemoteOnly"
defaultredirect= "Error.aspx"
<error statuscode= "440" redirect= "err440page.aspx"/>
<error statuscode= "redirect=" err500page.aspx "/>"
/>
I.mode: Has on,off,remoteonly 3 kinds of state. On indicates that custom information is always displayed; Off indicates that detailed asp.net error messages are always displayed; RemoteOnly indicates that custom information is displayed only for users who are not running on the local Web server.
Ii.defaultredirect: The URL address for redirection when an error occurs. is optional.
Iii.statuscode: Indicates an error status code indicating a specific error state.
IV. Redirect: URL for error redirection.
5.<globalization> Festival
Format:
<globalization
Requestencoding= "Utf-8"
Responseencoding= "Utf-8"
Fileencoding= "Utf-8"
/>
I.requestencoding: It is used to check each code that is sent for a request.
Ii.responseencoding: Used to check the response content encoding of the postback.
Iii.fileencoding: Used to check the default encoding for file resolution such as Aspx,asax.
6.<sessionstate> Festival
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: Divided into off,inproc,stateserver,sqlserver several states
mode = InProc stored in Process features: Best performance, fastest, but not shared across multiple servers. mode = "stateserver" stored in the state Server features: Use this method when you need to maintain user session information across servers. But the information is stored on the state server, and once the state server fails, the information is lost. mode= "SQL Server" is stored in SQL Server features: workloads can become larger, but information is not lost.
Ii. stateconnectionstring: Specifies the server name where the asp.net application stores the remote session state, default to native
Iii.sqlconnectionstring: When using a session-state database, set the connection string here
IV. Cookieless: When set to true, indicates that the customer is not identified by using cookie session state;
V. TimeOut: The time used to define the session-state store, exceeding the deadline, will automatically terminate the session.
7.<authentication> Festival
Format:
<authentication mode= "Forms" >
<forms name= ". Aspxuserdemo "loginurl=" Login.aspx "protection=" All "timeout="/>
</authentication>
<authorization>
<deny users= "?" />
</authorization>
I.windows: Using the IIS authentication method
Ii. Forms: Using forms-based Authentication
Iii. Passport: Use Passport cookie Authentication mode
IV. None: Do not use any authentication method
The attribute meaning of the embedded forms node inside:
I.name: Specifies the name of the HTTP cookie that completes the authentication.
Ii. Loginurl: If the URL of the page is not validated or redirected after the timeout, it is generally a login page that allows the user to log on again
Iii. Protection: Specifies how cookie data is protected.
Can be set to: all None encryption validation four ways of protection
A. All represents the encryption of data, and validation is done in two ways
B. None means that cookies are not protected.
C. Encryption means encrypting the contents of cookies
D. Validation means validation of cookie content
IV. TimeOut: Specifies the expiration time of the cookie. Log on again after the timeout.
Modifications to the Web.config file at run time do not require a restart of the service to take effect (note the exception to the:<processmodel> section). Of course, Web.config files can be extended. You can customize the new configuration parameters and write configuration section handlers to process them.
Web.config configuration file (default configuration settings) All of the following code should be located in the
<configuration>
<system.web>
And
</system.web>
</configuration>
, for learning purposes The following example omits this XML tag.
1, <authentication> Festival
Role: Configure ASP.net authentication support (for Windows, Forms, PassPort, none four). This element can only be declared at the computer, site, or application level. <authentication> elements must be used in conjunction with the <authorization> section.
Example:
The following example configures the site for forms-based authentication, and the page automatically jumps to the landing page when no logged user accesses the page that requires authentication.
<authentication mode= "Forms" >
<forms loginurl= "logon.aspx" name= ". Formsauthcookie "/>
</authentication>
Where the element loginurl represents the name of the landing page, name indicates the cookie name.
2, <authorization> Festival
Role: Controls client access to URL resources (such as allowing anonymous users to access). This element can be declared at any level (computer, site, application, subdirectory, or page). Must be used in conjunction with the <authentication> section.
Example: The following example prohibits access for anonymous users
<authorization>
<deny users= "?" />
</authorization>
Note: You can use User.Identity.Name to obtain the authenticated current username; You can use the Web.Security.FormsAuthentication.RedirectFromLoginPage method to redirect the authenticated user to the page that the user just requested . The specific
3, <compilation> Festival
Role: Configure all compilation settings used by asp.net. The default Debug property is True. You should set the program to false after it has been delivered for use (the Web.config file contains a detailed description, where the example is omitted)
4, <customErrors>
Role: Provides information about custom error messages for ASP.net applications. It does not apply to errors that occur in XML Web services.
Example: When an error occurs, the page is jumped to a custom error page.
<customerrors defaultredirect= "errorpage.aspx" mode= "RemoteOnly" >
</customErrors>
where element defaultredirect represents the name of the custom error page. The mode element indicates that custom (friendly) information is displayed for users who are not running on the local Web server.
5, Role: Configure ASP.net HTTP runtime settings. This section can be declared at the computer, site, application, and subdirectory levels.
Example: Controls the user uploads the file maximum is 4M, the longest time is 60 seconds, the maximum request number is 100
6, <pages>
Role: Identifies page-specific configuration settings (such as whether session state is enabled, view state, whether user input is detected, and so on). <pages> can be declared at the computer, site, application, and subdirectory levels.
Example: Do not detect potentially dangerous data in user-entered content in the browser (note: The default is detection, if you use no detection, to encode or verify the user's input, the encrypted view state is checked when the page is sent back from the client to verify that the view state has been tampered with on the client. (Note: This key is not validated by default)
<pages buffer= "true" enableviewstatemac= "true" validaterequest= "false"/>
7, <sessionState>
Role: Configures session state settings for the current application (such as setting whether session state is enabled, and where the session state is saved).
Example:
<sessionstate mode= "InProc" cookieless= "true" timeout= "/>"
</sessionState>
Note:
Mode= "InProc" means: Store session state locally (you can also choose to store on a remote server or a SAL server or not enable session state)
Cookieless= "true" means that session state is enabled if the user's browser does not support cookies (default is False)
timeout= "20" means the number of minutes that a session can be idle
8, <trace>
Role: Configure the ASP.net tracking service, mainly used to determine where the program test error.
Example: The following is the default configuration in Web.config:
<trace enabled= "false" requestlimit= "ten" 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" means that trace output can only be accessed through the trace utility;
Tracemode= "SortByTime" indicates that trace information is displayed in the order in which the trace is processed
Localonly= "True" indicates that the trace viewer (Trace.axd) is used only for hosting WEB servers
Customizing Web.config file Configuration
The custom Web.config file configuration section process is divided into two steps.
1. Declare the name of the configuration section and the name of the. NET Framework class that handles the configuration data in the section between the top <configSections> and </configSections> tags of the configuration file.
2. The actual configuration settings are made for the declared section after the <configSections> area.
Example: Create a section to store a database connection string
<configuration>
<configSections>
<section name= "appSettings" type= "System.Configuration.NameValueFileSectionHandler, System, version=1.0.3300.0, Culture=neutral, publickeytoken=b77a5c561934e089 "/>
</configSections>
<appSettings>
<add key= "Scon" value= "server=a;database=northwind;uid=sa;pwd=123"/>
</appSettings>
<system.web>
......
</system.web>
</configuration>
Accessing the Web.config file you can access the Web.config file example by using a configurationsettings.appsettings static string collection: Gets the connection string established in the above example. For example:
protected static string isdebug = configurationsettings.appsettings["Debug"
Second, web.config in the session configuration detailed
After opening the configuration file for an application web.config, we will find the following paragraph:
<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 is about configuring how the application stores session information. The following operations are mainly for this section of configuration. Let's take a look at what this section of the configuration contains. The syntax for the sessionstate node is this:
<sessionstate mode= "off| inproc| stateserver| SQL Server "
Cookieless= "True|false"
timeout= "Number of minutes"
Stateconnectionstring= "Tcpip=server:port"
sqlconnectionstring= "SQL connection string"
statenetworktimeout= "Number of seconds"
/>
Attributes must be: attribute option description
Mode setting where the session information is stored
Øoff is set to not use the session function,
Øinproc is set to store session in-process, which is the storage mode in ASP, which is the default value,
Østateserver is set to store sessions in a separate state service.
The Øsqlserver setting will store sessions in SQL Server.
The optional properties are: Attribute option description
Øcookieless set up where the client's session information is stored,
Øture uses cookieless mode,
Øfalse uses cookie mode, which is the default value,
Øtimeout settings after how many minutes after the server automatically discards session information, the default is 20 minutes.
stateConnectionString sets the server name and port number used when session information is stored in the status service, for example: "tcpip=127.0.0.1:42424". When the value of mode is StateServer, this property is required.
sqlConnectionString sets the connection string when connecting to SQL Server. For example, "Data source= localhost;integrated security=sspi;initial catalog=northwind". This property is required when the value of mode is SQL Server.
stateNetworkTimeout sets the TCP/IP connection between the Web server and the server that stores the state information when the session state is stored in the StateServer mode and after how many seconds of idle time. The default value is 10 seconds.
Asp. Storage of client session state in net
In our introduction to the session model above, you can find that the session state should be stored in two places, respectively, the client and server side. The client is only responsible for saving the SessionID of the corresponding Web site, while other session information is saved on the server side. In ASP, the client's SessionID is actually stored as a cookie. If a user chooses to disable cookies in the browser's settings, he or she will not be able to enjoy the convenience of the session, or even have access to some Web sites. In order to solve the above problems, in ASP. NET in the client's session information storage mode is divided into: cookies and cookieless two kinds.
Asp. NET, the session information is stored by default in the client or by using cookies. If we want to store session information in a cookieless way on the client side, the following methods are available:
Locate the root directory of the current Web application, open the Web.config file, and locate the following paragraph:
<sessionstate
Mode= "InProc"
Stateconnectionstring= "tcpip=127.0.0.1:42424"
sqlconnectionstring= "Data source=127.0.0.1; Trusted_connection=yes "
Cookieless= "false"
Timeout= "20"
/>
The cookieless= "false" in this passage is changed to: Cookieless= "true", so that the client's session information is no longer stored using cookies, but rather it is stored through the URL. Close the current IE, open a new IE, and visit the Web application again, and you will see something like this:
One of the http://localhost/MyTestApplication/(ulqsek45heu3ic2a5zgdl245)/default.aspx is the client's session ID, which is highlighted in bold. Note that this information is automatically added by IIS and does not affect previously normal connections.
Asp. Storage preparation for server-side session state in net:
For you to experience the phenomenon better, you can create a page called Sessionstate.aspx and add the following code to the <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") are 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>
<fontsize= "6" ><spanid= "Span1" runat= "Server"/></font>
This sessionstate.aspx page can be used to test whether session information has been lost on the current server.
To store server session information in a process
Let's go back to the paragraph in the Web.config document:
<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 value of mode is InProc, it indicates that the server is using this mode.
This approach, like the pattern in previous ASP, is where the server stores session information in the IIS process. This information will be lost when IIS is shut down and reset. But this model also has its own biggest advantage, is the highest performance. All session information should be stored in the IIS process, so IIS can quickly access this information, which is much faster than storing session information outside of the process or storing the session information in SQL Server. This pattern is also the default way of ASP.net.
Okay, now let's do an experiment. Open just the Sessionstate.aspx page, enter some characters, so that it stored in the session. Then, let's get IIS back up. Note that instead of stopping the current site from starting again, click the right mouse button on the local Machine name node in IIS and select Restart IIS. (When you want to use NT4, restart IIS must restart the computer to do, Microsoft is really @#$%^&) back to the Sessionstate.aspx page, check the session information just now, found that the information has been lost.
Storing server session information outside the process
First, let's open the Admin tool-> Service and find the service named: ASP.net State Service to launch it. In fact, this service is to start a process to save session information. After starting this service, you can see a process called Aspnet_state.exe from the Windows Task Manager-> process, which is the process of saving session information.
Then, return to the previous paragraph in the Web.config file and change the value of mode to StateServer. After saving the file, reopen an IE, open the sessionstate.aspx page, and save some information to the session. At this point, let us restart IIS, and then go back to the sessionstate.aspx page to see the session information just now, found not lost.
In fact, the way in which session information is stored outside the process means that it is not only possible to store information in a native process, but also to store session information in the process of other servers. Instead of changing the value of mode to StateServer, you need to configure the corresponding parameters in stateConnectionString. For example your calculation you are 192.168.0.1, you want to store the session in the IP-192.168.0.2 computer process, you need to set this: stateconnectionstring= "tcpip= 192.168.0.2:42424 ". Of course, don't forget to load the. NET Framework on a 192.168.0.2 computer and start the ASP.net State Services service.
To store server session information in SQL Server
First of all, let's do some preparatory work. Start SQL Server and SQL Server Agent service. Executes a script file called InstallSqlState.sql in SQL Server. This script file creates a database in SQL Server to store session information specifically, and a SQL Server Agent job that maintains the session information database. We can find that file in the following path:
[System Drive]winntmicrosoft.netframework[version]
Then open the Query Analyzer, connect to the SQL Server server, open the file just now and execute. Wait a moment, the database and the work is established. At this point, you can open Enterprise Manager, see a new database called ASPState. But this database is just a few stored procedures, no user table. In fact, session information is stored in the ASPStateTempSessions table of the tempdb database, and another Aspstatetempapplications table stores application object information in ASP. The two tables were also created by the script just now. In addition to view the Management->sql Server Agent-> job, found also a job called aspstate_job_deleteexpiredsessions, this assignment is actually every minute to ASPStateTempSessions Table to delete expired session information.
We then return to the Web.config file and change the value of mode to SQL Server. Note that you also have to modify the value of the sqlConnectionString in the following format:
sqlconnectionstring= "Data source=localhost; Integrated SECURITY=SSPI; "
Where data source refers to the IP address of the SQL Server server, if SQL Server and IIS are a machine, write 127.0.0.1. Integrated SECURITY=SSPI means to use Windows Integrated authentication so that access to the database will be done as asp.net, and by so doing, you can get more SQL than the userid=sa;password= password Better security for the server authentication method. Of course, if SQL Server is running on another computer, you may need to maintain the consistency of both sides of the authentication through the Active Directory domain.
Again, let's do an experiment. Adding session information to the sessionstate.aspx, it is found that session information already exists in SQL Server, even if you restart the computer, the session information just now will not be lost. Now that you've seen exactly what the session information looks like, and it's stored in SQL Server, it's up to you to see what you can do.
Summarize
Iii. asp.net general settings for form authentication
asp.net general settings for form authentication:
1: In Web.config, add form certification;
<authentication mode= "Forms" >
<forms name= "auth" loginurl= "index.aspx" timeout= "></forms>"
</authentication>
<authorization>
<deny users= "?"/>
</authorization>
2: If there is a registration page should also allow anonymous users to call the registration page for registration;
The following code should be between <configuration><system.web> and should not be included in the <SYSTEM.WEB> Between </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 the successful login to create an authentication ticket, indicating that has passed the certification of legitimate users;
if (login successful)
System.Web.Security.FormsAuthentication.SetAuthCookie (user name, false);
Iv. access to Web.config files
Access <appSettings> configuration section:
String Isdebug =system.configuration.configurationsettings.appsettings["Scon"]. ToString ();
Access <connectionStrings> configuration section:
String sqlconstr=system.configuration.configurationmanager.connectionstrings["Sqlconstr"]. ToString ();