Detailed Web. config file in C #

Source: Internet
Author: User
Tags configuration settings

Understanding the Web. config file in C # in a detailed

The Web. config file is an XML text file that is used to store configuration information for an ASP. NET Web application, such as the most commonly used settings for the authentication of an ASP. NET Web application, which can appear in every directory of the application. When you pass. NET creates a new Web application, by default, a default Web. config file is automatically created 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 under that subdirectory. It can provide configuration information other than the configuration information inherited from the parent directory, or you can override or modify the settings defined in the parent directory.

Modifications to the Web. config file at run time do not need to restart the service to take effect (note:<processmodel> section exception). Of course, the Web. config file 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>
, the following example omits this XML tag for learning purposes.

1. <authentication> Festival
Role: Configure ASP. NET authentication support (for Windows, Forms, PassPort, none of the four). This element can only be declared at the machine, site, or application level. < authentication> elements must be used in conjunction with the <authorization> section.

Example:

The following example configures a site for forms-based authentication, and when no logged-on user accesses a webpage that requires authentication, the page automatically jumps to the landing page.
<authentication mode= "Forms" >
<forms loginurl= "logon.aspx" name= ". Formsauthcookie "/>
</authentication>
where 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 user 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 disables access for anonymous users
<authorization>
<deny users= "?" />
</authorization>
Note: You can use User.Identity.Name to obtain the current user name that has been verified, and 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
Function: Configures all compilation settings used by ASP. The default Debug property is "True". It should be set to false after the program has been compiled for delivery (the Web. config file has a detailed description, omitting the example here)

4. <customErrors>
Role: Provides information about custom error messages for ASP. It does not apply to errors that occur in XML Web services.

Example: When an error occurs, the Web page jumps to the 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 the ASP. NET HTTP runtime settings. This section can be declared at the machine, site, application, and subdirectory levels.

Example: Control user upload file up to 4M, maximum time 60 seconds, maximum number of requests 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 machine, site, application, and subdirectory levels.

Example: Do not detect a user's input in the browser for potentially dangerous data (note: The item is detected by default, if you use no detection, one to encode or verify the user's input), the encrypted view state is checked when the page is posted back from the client to verify that the view state has been tampered with on the client. (Note: This item is not verified 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, session state save location).

Example:
<sessionstate mode= "InProc" cookieless= "true" timeout= "/>"
</sessionState>
Note:
Mode= "InProc" means: Store session state locally (you can also choose to store it in a remote server or SAL server or do not enable session state)
Cookieless= "True" indicates that session state is enabled if the user's browser does not support cookies (default = False)
Timeout= "20" indicates the number of minutes that a session can be idle

8. <trace>
Role: Configure the ASP. NET tracking service, mainly used for program testing to determine where errors.

Example: The following is the default configuration in Web. config:
<trace enabled= "false" requestlimit= "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" means to display trace information in the order in which the traces are processed
Localonly= "True" indicates that the trace viewer (Trace.axd) is used only for hosting WEB servers

Customizing the Web. config file configuration

Customizing the Web. config file configuration section is a two-step process.
1. Declare the name of the configuration section between the <configSections> and </configSections> tags at the top of the configuration file and the name of the. NET Framework class that handles the configuration data in that section.
2. Do the actual configuration settings for the declared section after the <configSections> area.

Example: Creating 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 the ConfigurationSettings.AppSettings static string collection: Gets the connection string established in the example above. For example:
protected static string isdebug = configurationsettings.appsettings["Debug"]

Ii. detailed session configuration in Web. config

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 the deployment. Let's take a look at the meaning of the content contained in this section of the configuration. 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"
/>

Required properties are

Property Options Description
Mode settings where to store the session information
? OFF is set to not use the session function,
? The InProc is set to store the session in-process, which is the storage method in ASP, which is the default value,
? The StateServer is set to store the session in a separate state service,
? SQL Server settings stores the session in a

The optional properties are:

Property Options Description
? Cookieless set where the client's session information is stored,
? Ture using cookieless mode,
? False using cookie mode, which is the default value,
? Timeout sets the number of minutes after which the server automatically discards session information, which defaults to 20 minutes.
stateConnectionString sets the server name and port number used when the session information is stored in the State service, for example: "tcpip=127.0.0.1:42424". When the value of mode is StateServer Yes, 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 settings when the session state is stored using StateServer mode, the TCP/IP connection to the server that stores the state information is disconnected after the number of seconds that the Web server is idle. The default value is 10 seconds.

Asp. The storage of client session state in net
In the introduction of the session model above, we can find that the session state should be stored in two places, namely the client and server side. The client is only responsible for saving the SessionID of the corresponding website, while the other session information is saved on the server side. In ASP, the SessionID of the client is actually stored in the form of 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 certain websites. In order to solve the above problems, in ASP. NET client's session information storage methods are divided into: two kinds of cookies and cookieless.
Asp. NET, by default, the session information is stored on the client or using a cookie. If we want to store session information as a client using cookieless, here's how:
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 paragraph is replaced by the following: Cookieless= "true", so that the client session information is no longer stored using a cookie, but rather it is stored through a URL. Close the current IE, open a new IE, revisit the Web application, and you will see something like this:
In http://localhost/MyTestApplication/(ulqsek45heu3ic2a5zgdl245)/default.aspx, the client's session ID is marked in bold. Note that this information is automatically added by IIS and does not affect the previous normal connection.

Asp. The storage of server-side session state in net

Preparatory work:
For you to experience the experiment better, you can create a page called sessionstate.aspx, and then 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") 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 if the session information is missing on the current server.

Storing server session information in a process
Let's go back to the paragraph in the Web. config file just now:
< 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 is the same as in the previous ASP, where the server stores session information in the IIS process. When IIS shuts down and restarts, this information is lost. But this model also has its own greatest benefit, 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 out of process or storing session information in SQL Server. This mode is also the default for ASP.
Okay, now let's do an experiment. Open the Sessionstate.aspx page and enter some characters to store it in the session. Then, let's let IIS restart. Note that instead of stopping the current site from starting, you can choose to restart IIS by right-clicking on the node of the native machine name in IIS. (If you want to use NT4, restart IIS must restart the computer before the line, Microsoft really @#$%^&) back to the Sessionstate.aspx page, check the session information just now, found that the information has been lost.

Store server session information outside the process
First, let's open the management tools, service, and find a service named: ASP. NET State service to start it. In fact, the service is to start a process to save the session information. After starting this service, you can see a process called Aspnet_state.exe from the Windows Task Manager, which is the process in which we save the session information.
Then, go back to the above 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 view the session information just now, found not lost.
In fact, the way the session information is stored out-of-process refers not only to the process of storing information in the local computer, but also to the process of storing the session information in other servers. In this case, you need not only change the value of mode to StateServer, but also configure the corresponding parameters in the stateconnectionstring. For example, your calculation is 192.168.0.1, and you want to store the session in the process of the IP-192.168.0.2 computer, you need to set it up like this: stateconnectionstring= "tcpip= 192.168.0.2:42424 ". Of course, don't forget to load the. NET Framework in the 192.168.0.2 computer and start the ASP.

Store the server session information in SQL Server
First of all, let's do some preparatory work. Start SQL Server and the SQL Server Agent service. Execute a script file called InstallSqlState.sql in SQL Server. This script file will create a database in SQL Server dedicated to storing session information, and a SQL Server Agent job that maintains the session information database. We can find the file in the following path:
[System drive]\winnt\microsoft.net\framework\[version]\
Then open Query Analyzer, connect to the SQL Server server, open the file you just made and execute. Wait a moment, the database and the job is set up. At this point, you can open Enterprise Manager and see a new database called ASPState. But this database is just a few stored procedures, no user tables. The session information is actually stored in the ASPStateTempSessions table in the tempdb database, and the other Aspstatetempapplications table stores the Application object information in the ASP. These two tables were also created by the script just now. In addition to view the Management->sql Server Agent----jobs, found also a job called aspstate_job_deleteexpiredsessions, the job is actually every minute to go to ASPStateTempSessions Table to delete the expired session information.
Next, we go back to the Web. config file and change the value of mode to SQL Server. Note that you also want to modify the value of the sqlconnectionstring at the same time, in the 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 that Windows Integrated authentication is used, so that access to the database is made as an ASP, and by this configuration, SQL can be obtained that is more than using the userid=sa;password= password Better security for server authentication. Of course, if SQL Server is running on another computer, you may need to maintain the consistency of validation on both sides of the way through Active Directory domains.
Again, let's do an experiment. Add session information to the sessionstate.aspx, then found that the session information already exists in SQL Server, even if you restart the computer, just the session information will not be lost. Now that you've seen exactly what the session message looks like, and it's stored in SQL Server, you can see what you're doing.

Summarize
Through this article, you can see the management and maintenance of the session, ASP. NET than ASP has made great progress, we can more arbitrarily choose the appropriate method. For enterprise-class applications, this is undoubtedly beneficial for server synchronization, server stability, and reliability. I believe that with the strong support of Microsoft, the next generation of e-commerce platform will be built better!
At the same time, you will find that the entire technology includes the integration of operating systems, Web services, and database technologies. I believe that maybe Windows is not stable with UNIX, IIS is not Apache stable, SQL Server is not as powerful as Oracle, but who can bring them together so perfectly? So, although Microsoft is not too strong in every respect, but if Microsoft's things are integrated together, who dare say he is not strong? Microsoft is Microsoft!

Three, ASP. General Settings for form authentication

asp.net General settings for form authentication:
1: In Web. config, add form authentication;
   < Authentication mode= "Forms";
            <forms Name= "auth" loginurl= "index.aspx" timeout= "" "></FORMS>
</authentication>
<authorization
        <deny users= "?"/>
</authorization>
2: If you have a registration page, you should also allow anonymous users to call the registration page to register;
The following code should be between <configuration><system.web> and should not be included in the <SYSTEM.WEB> Between </system.web>; The
----------------means that anonymous users are allowed access to 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 login, indicating that a legitimate user has passed the authentication;
if (login successful)

system.web.security.formsauthentication.setauthcookie (user name, false);

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.