Methods to Improve ASP. NET Website Performance

Source: Internet
Author: User
Tags net thread send cookies website performance

ASP. NET has many secrets. When you understand these secrets, you can make your ASP. NET applicationProgramThis greatly improves the performance. For example, when using membership and profile for authentication and authorization, you can simply modify membership and profile to Improve the Performance of authentication and authorization. asp.. Net HTTP pipeline through adjustment to avoid unnecessary httpmodules; in addition, the browser page cache can save a lot of download time for repeated browsing; loading the on-demand UI can make the website faster and smoother. Finally, t applies CDN (cotent delivery networks) and HTTP cache header to make the website faster. Next let's discuss these skills separately to improve the performance of our ASP. NET Website.

1 ASP. NET pipe Optimal Configuration

Each time a user requests a website, there will be many ASP. net by default, httpmodules interrupts the request and performs some processing. For example, sessisonstatemodule interrupts each request, parses the session cookie information, and loads the appropriate session to httpcontent. however, these default httpmodules are not all necessary. For example, if you do not apply Forms authentication for user authentication, you do not need formsauthentication module.

The default modules is in the machine. config file (where the file is located:$ Windows $ \ Microsoft. NET \ framework \ $ version $ \ configDirectory), which is defined as follows :.

 <  Httpmodules  > 
< Add Name = "Outputcache" Type = "System. Web. caching. outputcachemodule" />
< Add Name = "Session" Type = "System. Web. sessionstate. sessionstatemodule" />
< Add Name = "Windowsauthentication"
Type = "System. Web. Security. windowsauthenticationmodule" />
< Add Name = "Formsauthentication"
Type = "System. Web. Security. formsauthenticationmodule" />
< Add Name = "Passportauthentication"
Type = "System. Web. Security. passportauthenticationmodule" />
< Add Name = "Urlauthorization" Type = "System. Web. Security. urlauthorizationmodule" />
< Add Name = "Fileauthorization" Type = "System. Web. Security. fileauthorizationmodule" />
< Add Name = "Errorhandlermodule" Type = "System. Web. Mobile. errorhandlermodule,
System. Web. Mobile, version = 1.0.5000.0,
Culture = neutral, publickeytoken = b03f5f7f11d50a3a" />
</ Httpmodules >

You want. add the <remove> node in config to remove unnecessary httpmodules. For example, if a website uses forms authentication based on the data base and does not use any session, it can be stored on the web. add the following nodes to config:

 <  Httpmodules  > 
<! -- Remove unnecessary HTTP modules for faster pipeline -->
< Remove Name = "Session" />
< Remove Name = "Windowsauthentication" />
< Remove Name = "Passportauthentication" />
< Remove Name = "Anonymousidentification" />
< Remove Name = "Urlauthorization" />
< Remove Name = "Fileauthorization" />
</ Httpmodules >
2 ASP. NET Process Optimization Configuration

ASP. the Net Process Module configures many process-level attributes, such as ASP. the number of threads that can be used by. net. The number of requests that need to wait when the I/O thread completes the work. The default configuration has many restrictions, but now the hardware is getting cheaper and cheaper. The dual-core processing and GB memory are changed to standard configurations, so we need to adjust the default configuration, allow the Asp.net process to use more system resources.

By default, the Asp.net process is configured in the mechine. config file.

<System. Web>

<Processmodel AutoConfig= "True" />

We can adjust the default configuration to specify different values for each attribute to customize the working model of the Asp.net thread. For example:

 <  Processmodel  

Enable = "True"

Timeout = "Infinite"

Idletimeout = "Infinite"

Shutdowntimeout = "00:00:05"

Requestlimit = "Infinite"

Requestqueuelimit = "5000"

Restartqueuelimit = "10"

Memorylimit = "60"

Webgarden = "False"

Cpumask = "0 xffffffff"

Username = "Machine"

Password = "Autogenerate"

Loglevel = "Errors"

Clientconnectedcheck = "00:00:05"

Comauthenticationlevel = "Connect"

Comimpersonationlevel = "Impersonate"

Responsedeadlockinterval = "00:03:00"

Responserestartdeadlockinterval = "00:03:00"

AutoConfig = "False"

Maxworkerthreads = "100"

Maxiothreads = "100"

Minworkerthreads = "40"

Miniothreads = "30"

Servererrormessagefile = ""

Pingfrequency = "Infinite"

Pingtimeout = "Infinite"

Asyncoption = "20"

Maxappdomains = "2000"

/>

The above attributes are basically the default values used, except the following:

    • Maxworkerthreads: the default value of maxworkerthreads is 20/process. In a dual-core processor server, 40 threads are allocated to Asp.net, which means that Asp.net of the dual-core server can only process 40 requests in parallel at the same time, to assign more threads to Asp.net, I changed the value of maxworkerthreads to 100. Note that if Asp.net is used up and a new request comes in, Asp.net will put the new request in the waiting queue until a thread is released, therefore, if your application calls many web services or has many I/O operations, and these operations do not occupy too much CPU resources, you can increase the value of maxworkerthreads.
    • Maxiothreads: the default value of maxiothreads is 20/process. On a dual-core processor, 40 threads are also allocated to Asp.net for I/O operations, this also means that on a dual-core processor, Asp.net can only process 40 I/O requests in parallel at the same time. I/O requests can be file read/write, database operations, and Web service calls. Therefore, if your application server has enough resources to process these operations in parallel, you can set the value of maxiothreads to a greater value, such as 100.
    • Minworkerthreads: the default value of minworkerthreads is 1, which indicates the minimum number of auxiliary threads allocated to Asp.net.
    • Miniothreads: the default value of minworkerthreads is 1, which indicates the minimum number of I/O auxiliary threads allocated to Asp.net.
    • Memorylimit: specifies the maximum memory size that can be used by the auxiliary process before ASP. NET starts a new process and reallocates existing requests as a percentage. The default value of memorylimit is 60. If your server has only your own applications and there is no other memory-consuming service, you can set up memorylimit to a larger value, such as 80.

In addition to processmodel, another important node should be configured, that is, you can configure the maximum number of concurrent requests allowed for an IP address on the system. NET node:

<System.net> 

<Connectionmanagement>

<Add Address= "*" Maxconnection= "100" />

</Connectionmanagement>

</System.net>

The default value of maxconnection is 2, which means that you cannot request more than 2 IP addresses in your application at the same time. Therefore, if your application has made many calls to a specific server, you can set the maxconnection value to a larger value. For example, if I set it to 100 here.

 

3. What must be done before the application goes online

If membership provider is applied to your application, you have to make some adjustments to Web. config before the application goes online:

  • Add the applicationname attribute to profile provider. If you do not specify the applicationname value, profile provider sets the value to a guid, this means that the applicationname on your development machine is a guid and the application on the product server is another guid, so you have not reused the data about membership in the database on the development machine. Therefore, specify the applicationname value in the following format:

         <  Profile   Enabled  = "True"  >  
    < Providers >
    < Clear />
    < Add Name = "..." Type = "System. Web. profile. sqlprofileprovider"
    Connectionstringname = "..." Applicationname = "Yourapplicationname"
    Description = "..." />
    </ Providers >
  • Every time a request is complete, the profile provider automatically saves the profile, which reduces the performance of our application because of a large number of non-essential update operations, so disable the automatic saving of profile and display it through profile when necessary. save.
    <Profile Enabled= "True" Automaticsaveenabled= "False" >
  • Role manager needs to query the database every time to determine a user's role, which is also a huge performance loss. We can solve this problem by caching the user's role in the cookie, however, please note that the maximum cookie capacity is 2 kb, so if we have many users and each user has a particularly large number of roles, it may exceed the cookie capacity, of course, this is a minority case, so we can usually cache user role information in cookies through the following settings to reduce the number of database accesses.
    <Rolemanager Enabled= "True" Cacherolesincookie= "True" >
4. cache Ajax requests on the client

The browser can cache images, JS files, and CSS files, and the browser can also cache xml http calls (of course, this requires xml http to send calls in get mode). This cache is based on URL, when we send a request, if it is the same as the previous request URL, then the browser will respond from the cache, rather than asking the server again, which can save some time. Generally, the browser caches the results of all http get requests. Therefore, if we want xml http to send requests in get mode, and the server returns a specific header to tell the browser to cache the results, in future requests, we can get a response directly from the cache, thus saving a lot of time.

On the pageflakes website, the author caches the user status. Therefore, if a user logs on to the website again, the user will obtain a cached page from the browser cache instead of requesting the server again, therefore, the second access is much faster. In addition, the author caches the operation results of many users. Therefore, when users perform the same operation again, the cached results will appear quickly, this gives users a better experience.

Therefore, if an Ajax request is called using http get, a specific HTTP header should be returned to the browser to cache the request results. Below are two different methods, one of which can be used:

 
HTTP/1.1 200 OK
 
Expires: Fri, 1 Jan 2030
 
Cache-control: Public

The above header tells the browser to cache the request results to 2030. Therefore, if we send the same xml http request before 2030, the browser will directly read the results from the cache without re-requesting the server. In addition, there is a more advanced header used to control the cache of the Request results. The following header indicates that the browser also caches the request results for 60 minutes and then re-Requests the results after 60 minutes,

 
HTTP/1.1 200 OK
 
Cache-control: private, must-revalidate, proxy-revalidate, Max-age = 60

Let's try to add the above header to the ASP. NET web service response:

 
[Webmethod] [scriptmethod (usehttpget =True)]
Public StringCachedget ()
{
Timespan cacheduration = timespan. fromminutes (1 );
Context. response. cache. setcacheability (httpcacheability. Public );
Context. response. cache. setexpires (datetime. Now. Add (cacheduration ));
Context. response. cache. setmaxage (cacheduration );
Context. response. cache. appendcacheextension (
"Must-revalidate, proxy-revalidate");

ReturnDatetime. Now. tostring ();
}

The aboveCodeThe following response headwers will be generated:

 

We can see that the expires attribute is correctly set, but the cache-control attribute is not correctly set, and Its max-age value is 0 rather than 60, in this way, the browser will not do any caching, so when we re-request, we will still request the server, instead of returning results from the cache.

This is a bug in Asp.net 2.0. You cannot change the value of max-age because before processing a Web Services request, asp.net Ajax framework intercepts the request and mistakenly sets max-age to 0, which means that the browser will not cache the Ajax response.

However, by decompiling the httpcachepolicy code, we found the following code segment:

Somehow, only when "If(! This. _ ismaxageset | (delta< This. _ Maxage ))", The value of _ maxage is set. This is incorrect, because it prevents the value of _ maxage from being set to a value greater than the current value. Therefore, we need to use reflection to bypass the setmaxage method to set the value of _ maxage:

[Webmethod] [scriptmethod (usehttpget =True)]
Public StringCachedget2 ()
{
Timespan cacheduration = timespan. fromminutes (1 );

Fieldinfo maxage = context. response. cache. GetType (). getfield ("_ Maxage",
Bindingflags. instance | bindingflags. nonpublic );
Maxage. setvalue (context. response. cache, cacheduration );

Context. response. cache. setcacheability (httpcacheability. Public );
Context. response. cache. setexpires (datetime. Now. Add (cacheduration ));
Context. response. cache. appendcacheextension (
"Must-revalidate, proxy-revalidate");

ReturnDatetime. Now. tostring ();
}

The above code returns the following header:

Now we can see that the value of max-age is 60, and the browser will cache the result for 60 minutes. If you make the same call within 60 minutes, the browser will respond from the cache. One minute later, when the cache expires, the browser will automatically send a request, and the request code is as follows:

FunctionTestcache ()
{
Testservice. cachedget (Function(Result)
{
Debug. Trace (result );
});
}

Please note that there is another problem here, because the default trust level of Asp.net Ajax is moderate,

 
<System. Web>
<Trust Level= "Medium"/>

However, our cachedget2 method uses reflection, so moderate trust is not enough. We need to modify the Web. config file as follows:

 
<System. Web> 
<Trust Level= "Full"/>
5. Better use of consistent URLs in application browser cache

The foundation of browser cache is URL. When a URL changes, the browser will request the page again from the server. We can change the URL through different query parameters. For example, We cache the default. aspx page in the cache. If we request the default. aspx /? 1 page. Although the operation is the same, the browser will still request the server again. In addition, if the settings are made in the header, the new request results will also be cached. Therefore, make sure that consistent URLs are used. A common error is that WWW is omitted in the URL, for example, www.cnblogs.com/zhangronghuaand cnblogs.com/zhangronghuawill be stored separately.

Set the cache period of static content to a longer value.

You can set a long cache period for a static file, for example, one month. If you think you should cache the file for two days, then after you change the file, the user can quickly get the new file, which is wrong, after you update a file cached by expires, the new user will immediately get the changed file, and the old user can only get the changed file after the cache expires. So as long as you have applied expires to cache static files, you should set the expiration period as large as possible.

For example, if you set the cache cycle of a static file to three days, a user a accesses the page today and caches it for three days, another user B will visit the page tomorrow and cache the page as well. So if you change the file the day after tomorrow, user a will see the new file on the fourth day, and user B will see the new file on the fifth day, this will cause different users to see different files, which is not the expected result. If we change the file and want users to see the changed file immediately, we should use different URLs to access files.

Use cache-friendly directory structure

Try to put the files to be cached in a directory. For example, put all the images in the images directory instead of in different directories, in this way, we need to use consistent URLs throughout the website to request images.

Reuse public images

Sometimes, in order to write less paths, a public image is put into many different directories, so that we can only use the image name in the file to reference the image, instead of based on the same path, although this makes writing easier, it is not cache-friendly. Every copy of a public file is cached in the cache. So what we need to do is to put the public file in a unified directory and reference it with a relative path on the page.

After modifying the static file, remember to modify the file name.

After you modify a static file, do not think it is all right to modify the file. Because the static file will be cached on the client, after you modify the static file, remember to rename it, because this ensures that you can immediately see the modified file, instead of caching the file before modification in the browser cache.

Use the version number to access static files

If you do not want to rename a static file name every time you modify it, you can also use a URL with a version number to access the static file. For example, you can access a GIF file through a URL with a dummy query character, you can use/images/1.gif? When the 1.gif file is changed, you need to use/images/1.gif? V = 2 to access the 1.gif file. This ensures that the user can view the modified file immediately.

Place cached files in a separate domain

It is a good idea to put cached files in a separate domain. First, the browser also requests static files concurrently. Second, you do not need to send cookies to static files. When you place the static files and application scripts in the same domain, the browser will request the static files, send together the cookies generated by the application, which are not mandatory for static files. Therefore, if we put static files in a single domain, we need to avoid sending these cookies. For example, we can place static files in www.zhangronghua.com and our applications in www.application.com. www.zhangronghua.com does not have to be a real website, it can be just an alias and direct to a common directory with www.application.com.

SSL is not cached, so use it as appropriate

SSL is non-cached, so do not request static files through SSL. In addition, we should only use SSL on login and payment pages, in addition, SSL should not be used in the program. SSL requires encryption of requests and responses, so it increases the burden on the server, and the encrypted response content is longer, which consumes more bandwidth.

Http post requests are not cached

The browser only caches http get requests and does not Cache http post requests. If you want to cache a file, make sure to request the file in http get mode.

Show specified Content-Length attribute

When you request a dynamic content through web service or HTTP hadler, make sure that the Content-Length attribute of the response header is set. When the browser reads the content-lengtg attribute from the response header, it will optimize the response to increase the download speed. When Content-Length is specified, the browser uses a persistent connection to request resources, which avoids the browser from creating a new connection for each request.

How to cache static content in IIS

In IIS manager, right-click the application name and select "properties". We can see:

Select "enable content expiration" to cache static content. The specific settings are simple.

 

 

 

 

Related Article

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.