Detailed explanation of Web. config + Asp.net Optimization Method

Source: Internet
Author: User
This method not only stores session information outside the process, but also stores session information 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.

Next, We will 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
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;
BelowCodeIt should be between <configuration> <system. Web>, not between <system. Web>... </system. Web>. [Page]
---------------- 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"]
ASP. NET performance optimization.

(1) Select the session state storage mode
In the webconfig file, configure: <sessionstate mode = "??? "Stateconnectionstring =" TCPIP = FIG: 42424"
Sqlconnectionstring = "Data Source = 127.0.0.1; trusted_connection = yes"
Cookieless = "false" timeout = "20"/>

Asp.net can store session status information in three ways:
1. storage in the process: attribute mode = inproc
Features: it has the best performance and the fastest speed, but cannot be shared across multiple servers.

2. stored in the status server: attribute mode = \ "StateServer \"
Feature: This method is used to maintain user session information across servers.
However, the information is stored on the Status server. Once the status server fails, the information will be lost.

3. Stored in SQL Server: attribute mode = \ "sqlserver \"
Feature: the workload increases, but the information is not lost.
Add:
I. Because some pages do not require session status, you can disable the session Status:
The Code is as follows:

<% @ Page enablesessionstate = "false" %>

II. If the page needs to access session variables but cannot be modified, you can set the page session status to read-only: [Page]
The Code is as follows:
<% @ Page enablesessionstate = "false" %> You can select a method based on your needs.

(2 ). use Page. ispostback
page. ispostback indicates whether it is returned from the client. the value of "false" is not returned from the client during the initial operation. When an event on the page is triggered or the page is refreshed, the page is displayed. the value of ispostback is true because it is sent back.
this parameter is generally used in the page_load method:
private void page_load (Object sender, eventargs E)
{< br> If (! Page. ispostback)
{< br>; // code of the initialization page. The code is executed when the page is initialized for the first time. When the second request is sent back,
// The Code will not be executed again. Improve efficiency.
}< BR >}< br> ispostback is often used, because some controls must be kept in the status after initialization.
for example, if dropdownlist is initialized every time, the user will be initialized to the default value regardless of the option.

(3) Avoid using server controls
1. For general static display information, do not use the Server Control to display it. Because the server control needs to be sent back to the server for executionProgramThe execution efficiency is generally displayed using <div>.
If the server control is used, remove runat = \ "Server \" to Improve the efficiency.
2. Disable the status view of the server-side control. Some controls do not need to maintain their status. You can set its attribute to enableviewstate = false;
If the status view does not need to be maintained for the entire page control, you can set the status vision of the entire page to false:
The Code is as follows: <% @ page enableviewstate = \ "false \" %>
3. Configure in the web. config file:
ASP. NET sessionss can be configured in the sessionsstate element in Web. config or machine. config.
The following is an example of setting in Web. config:
<Sessionsstate timeout = "10" cookieless = "false" mode = "inproc"/>

(4) avoid using the DataGrid
We all know that the DataGrid is powerful. However, powerful functions increase performance overhead. Other controls are generally used: datalist [Page]
Or the Repeater control can implement, do not use the DataGrid whenever possible.

(5). String operations
1. Avoid packing. the operating efficiency of packing is relatively low.
For example, run two code segments:

String test = "";
For (for int I = 0; I <10000; I ++)
{
Test = test + I;
} And
String test = "";
For (for int I = 0; I <10000; I ++)
{
Test = test + I. tostring ();
}
The following code segment is obviously highly efficient. Because I is an integer type, the system needs to pack and convert I to string type before connection.

You can copy it to your machine and test it.
2. Use the stringbulider class
During string connection: String STR = str1 + str2 + ....;

Generally, it is better to use stringbuilder to replace the string class. stringbuilder to avoid performance loss caused by re-creation of the string object.
It is generally used to assemble SQL statements: stringbulider.
You can test it on your machine.
3. Try to use less:

Try
{}
Catch
{}
Finally
{} Statement. The execution efficiency of this statement is relatively low.

(6). Ado. Net Usage Optimization

1. Open and Close the database connection. Open the connection when you need to access the database. Close the connection immediately after the database is accessed.
For example, let's look at two code segments:
I.

Dataset DS = new dataset ();
Sqlconnection myconnection = new sqlconnection ("Server = localhost; uid = sa; Pwd =; database = northwind ");
Sqlcommand mycommand = new sqlcommand (strsql, myconnection );
Sqldataadapter myadapter = new sqldataadapter (querystr, connectionstr );
Myconnection. open (); // open the connection
For (INT I = 0; I <1000; I ++) // For Loop Simulation of business logic operations before data is obtained
{
Thread. Sleep (1000 );
}
Myadapter. Fill (DS );
For (INT I = 0; I <1000; I ++) // For Loop Simulation of business logic operations after data is obtained
{
Thread. Sleep (1000 );
}
Myconnection. Close (); // close the connection

II.

Dataset DS = new dataset ();
Sqlconnection myconnection = new sqlconnection ("Server = localhost; uid = sa; Pwd =; database = northwind ");
Sqlcommand mycommand = new sqlcommand (strsql, myconnection );
Sqldataadapter myadapter = new sqldataadapter (querystr, connectionstr); [Page]
For (INT I = 0; I <1000; I ++) // For Loop Simulation of business logic operations before data is obtained
{
Thread. Sleep (1000 );
}
Myconnection. open (); // open the connection
Myadapter. Fill (DS );
Myconnection. Close (); // close the connection
For (INT I = 0; I <1000; I ++) /// For Loop Simulation of business logic operations after data is obtained
{
Thread. Sleep (1000 );
}
The display II code is much better than I code, and I occupies the connection early. If there are many users, the connection pool may be full. Serious crashes.

2. Database Query
I. Generate SQL statements directly. SQL Server needs to compile SQL Server every time, which won't be greatly improved in terms of performance. In addition, it is not safe enough. Easy to attack.
Ii. use SQL commands with parameters. In this way, SQL Server only compiles the program once. For different parameters, you can repeat the compiled command. Improved performance.
Iii. use SQL Server Stored Procedures. Compile once. It is independent and easy to modify and maintain. It can send Statements multiple times at a time, reducing network

Traffic. Stored procedures are not necessarily more efficient than statements. If the business logic is complex, sometimes statements are more efficient than stored procedures.

(6) Cache Optimization
There are two types of cache: Page cache and API cache.
1. Use Page cache and fragment Cache

<% @ Outputcache duration = "5" varybyparam = "NONE" %>
<% @ Outputcache duration = 60 varybyparam = "textbox1, textbox2" %> Note: duration is used to set the cache expiration time;
Varbyparam is used to set whether the parameter changes. If none is used, all parameters use the same cache. [Page]
When textbox1 is set, it is cached based on different textbox1 values. When there are multiple parameters, the cache should be combined;
2. API cache. Used in applications
I. An example of Cache Usage:
Http://blog.csdn.net/chengking/archive/2005/10/03/494545.aspx
Ii. Note the differences between page. cache and httpcontext. Current. Cache during use:
They refer to the same object. In the page, page. cache. use httpcontext. current. cache uses httpruntime in some events because it does not have httpcontext. cache.

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.