Understanding Web.config Documents

Source: Internet
Author: User
Tags configuration settings error status code http cookie session id parent directory sessions web services

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> Festival
The root element, and the other sections are inside of it.
2.<appsetting> Festival
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>
An error redirection page was defined.
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: Starts ASPX debugging when true, and does not start ASPX debugging for false, which can improve application running
Performance at the time. 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
Here is a detailed description of this attribute: http://blog.csdn.net/chengking/archive/2005/10/27/518079.aspx
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.

Optional properties are: Property option description  
ø         cookieless set the client's session information stored to where,
ø         Ture uses cookieless mode,
ø          false Use cookie mode, which is the default value,
ø         timeout Set the server to automatically discard session information after the number of minutes after the default is 20 minutes. The
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. &NBSP
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. &NBSP
stateNetworkTimeout Sets the TCP/IP connection between the Web server and the server where the state information is stored when the session state is stored in StateServer mode, after a few 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:
In order 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>
< hrsize= "1" >
< 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.

Store server session information in process  
Let's go back to the paragraph 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= "a"  
/>
When the value of mode is InProc, 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.
OK, 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]/winnt/microsoft.net/framework/[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
Through this article, you can see in the session Management and maintenance, ASP. NET than the ASP has made great progress, we can more randomly select the appropriate method. For enterprise-class applications, this is undoubtedly for the server synchronization, server stability, reliability are beneficial. I believe that with the strong support of Microsoft, a new generation of E-commerce platform will be built better.
At the same time, you will find that the entire technology includes the operating system, Web services and the integration of a variety of database technologies. I believe that perhaps windows is not stable with UNIX, IIS is not Apache stable, SQL Server is not powerful Oracle, but who can make them so perfectly linked together. So, although every aspect of Microsoft is not too strong, but if the Microsoft's things are integrated together, who dare to say he is not strong. Microsoft is Microsoft.

Third, asp.net about form certification general settings
asp.net about form authentication General settings:
1: In web.config, add form certification; &NBSP
   < 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>; The
----------------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 to create an authentication ticket after a successful logon. A legal user who indicates that it has passed the certification;
if (login succeeded)

System.Web.Security.FormsAuthentication.SetAuthCookie (user name, false);
Iv. access to Web.config files
You can access the Web.config file example by using a collection of configurationsettings.appsettings static strings: Get the connection string created in the above example. For example:

protected static string isdebug = configurationsettings.appsettings["Scon"]
The article was transferred from Doorle's blog-blog: http://www.doorle.cn/blog/article.asp?id=923

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.