Asp.net website Optimization

Source: Internet
Author: User
Tags website performance metabase

Reading directory

  • Start
  • Configure OutputCache
  • Enable content expiration
  • Solve resource file upgrade Problems
  • Enable Compression
  • Delete useless HttpModule
  • Other Optimization Options

This article will introduce some methods used to optimize ASP. NET Website performance. These methods do not need to modify the program code. They are mainly divided into two aspects: 1. Using ASP. NET's own scalability for optimization. 2. Optimize IIS settings.

Back to Top to configure OutputCache

It is estimated that no one knows how to use cache to optimize website performance. ASP. NET provides the HttpRuntime. Cache object to Cache data and the OutputCache command to Cache the output of the entire page. Although the OutputCache command is more convenient to use and has very good results, we need to add such a command to those pages.

For pages with OutputCache configured, the browser caches the page response content after receiving the response from these pages. As long as the user does not force refresh the operation within the specified cache time, the server will not be requested again. For requests initiated by other browsers, if the cache page has been generated, then you can directly respond to the request from the cache to speed up the response. Therefore, the OutputCache command is meaningful for performance optimization (unless all pages are updated frequently ).

In the website optimization stage, we can use tools such as Fiddler to find outPages with almost no content changesTo set OutputCache for them. However, according to the traditional development process, we need to perform the following operations for each page file: 1. Check out the page file. 2. Add the OutputCache command. 3. republish the page. 4. Check in the file (if multiple branches are parallel, merge operations may be required ).These source code management systems will complicate a simple matter.Is there a simpler way to solve this problem?

Next, this article will introduce a method that uses ASP. NET's own scalability to set OutputCache parameters for pages in the form of configuration files. The other configuration file is an XML file with the following content:

"" """"                         """" ""  "" ""  

After reading this configuration, I think you can also guess what it can do.

Each line of configuration parameters specifies the parameters required by OutputCache for a page. The example file uses only two parameters. For other supported parameters, see OutputCache command.

To make this configuration file valid, configure the following content in web. config (for IIS7 ):

"" "" 

Here, I have registered an HttpModule, and all its code is as follows:

: {    SetOutputCacheModule()    {        xmlFilePath Combine(AppDomainAppPath, );        LoadConfig(xmlFilePath);    }    Init(app)    {        appPreRequestHandlerExecute (app_PreRequestHandlerExecute);    }    app_PreRequestHandlerExecute(sender, e)    {        app ()sender;        , settings Settings;        ( settings )            ();        setting ;        ( settingsTryGetValue(appRequestFilePath, setting) ) {            settingSetResponseCache(appContext);        }    }

The ConfigManager class is used to read the configuration file and enable the file dependency technology. After the configuration file is updated, the program automatically reloads the file:

{    CacheKey NewGuid()ToString();    s_loadConfigException;    , s_settings;    , Settings    {        {            exceptin s_loadConfigException;            ( exceptin )                exceptin;            s_settings;        }    }    LoadConfig(xmlFilePath)    {        , dict ;        {            config XmlDeserializeFromFile(xmlFilePath, UTF8);            dict configSettingsToDictionary(x xFilePath, OrdinalIgnoreCase);        }        ( ex ) {            s_loadConfigException SystemConfiguration(                xmlFilePath , ex);        }        ( dict ) {            dep (xmlFilePath);            CacheInsert(CacheKey, xmlFilePath, dep,                NoAbsoluteExpiration, NoSlidingExpiration, NotRemovable, CacheRemovedCallback);        }        s_settings dict;    }    CacheRemovedCallback(key, value, reason)    {        xmlFilePath ()value;        SystemThreadingSleep();        LoadConfig(xmlFilePath);    }}

With AutoSetOutputCacheModule, we can directly use the configuration file to set the OutputCache parameter for the page without modifying any pages. Is it easy to use?

Note: The MyMVC framework supports this function. All related functions can be obtained from the source code of the MyMVC framework.

Suggestions: Cache pages are an effective optimization method for pages that are rarely changed.

Back to Top to enable content expiration

Each website has some resource files (images, JS, CSS). Their output content is likely to remain unchanged over a long period of time compared to the ASPX page, IIS does not generate a Cache-Control response header when responding to such resource files. In this case, the browser may cache them and initiate another request (such as after restart). In short, the cache behavior is uncontrolled and the cache time is not long enough.

Have you ever thought about caching them in a browser for a long time?

To tell the browser to cache these files for a long time and reduce meaningless requests (improving page rendering speed), we can enable content expiration in IIS, IIS can generate a Cache-Control response header, clearly telling the browser how long the file will be cached.

In IIS6, this parameter is well found:

However, in IIS7, this parameter is not easy to find. You need to perform the following operations to find this parameter (Or website subdirectory) Node, double-click [HTTP Response Header]

Click the "set common headers" link on the right,

At this time, the following information is displayed:

Note:[Enable content expiration] This setting can be based on the entire website, sub-directories, or a specific file.

Note:If you set enable content expiration for a subdirectory or file in IIS7, the previous dialog box looks exactly the same. However, in IIS6, we can clearly understand what we are doing from the title bar of the dialog box:

Sometimes I feel that the IIS7 interface is regressing!

Finally, I want to say:You can enable content expiration for the entire website. The ASPX page will not be cached!

Some people may think about how long should I set the expiration time? Ten minutes, two hours, one day, or one month? In my opinion, the longer the time, the better. Some may say: What if I want to upgrade a JS file? How can I update it after a long time? If you ask me this question, I can only say that your code is unreasonable (after all, you cannot solve the upgrade problem). If you want to know the reason, please continue reading.

Go back to the top to solve the resource file upgrade problem

For some small websites, Usually deploy the resource file and program file together to a website. The following method may be used to reference JS or CSS files:

 

In this case, if the "enable content expiration" method is used, when the JS and CSS files need to be upgraded, because the browser cache has not expired, therefore, the server will not be requested, and the cached version will be used at this time, so various strange bugs may occur.

For the BUG mentioned above, I think the root cause is that the method of referencing JS and CSS files is flawed. The method does not take version upgrade into account at all. There are two correct methods: 1. add a version number to the file name, one file (jquery-1.4.4.min.js) for each version, as in jquery ). 2. Add a version number after the URL to invalidate the original URL.

The first method is because a new file is generated during each upgrade, so there is no cache problem. However, the cost of maintaining a large number of files may be relatively high. Therefore, I suggest using the second method to solve this problem.

In the sample code of MyMVC, I used the following method to reference these resource files:

RefCssFileHtml()RefJsFileHtml()

When running the page, the following output is generated:

 

The implementation code of these two tools and methods is as follows (in the sample code of MyMVC ):

s_root AppDomainAppPathTrimEnd();RefJsFileHtml(path){    filePath s_root pathReplace(, );    version GetLastWriteTimeUtc(filePath)TicksToString();    Format(, path, version);}RefCssFileHtml(path){    filePath s_root pathReplace(, );    version GetLastWriteTimeUtc(filePath)TicksToString();    Format(, path, version);}

The above method for obtaining the file version number is a simple solution. When HTML code is generated for each reference, the last modification time of the file will be accessed, which will bring a little read overhead to the disk. If you are worried that this implementation method may affect the performance, you can also add a configuration file to solve the problem (Please implement it yourself), for example, the following structure:

"" """"                     """" "" "" "" 

If you think this configuration file requires manual maintenance and is not automated enough, you can also use a program to automatically maintain a list during running. In short, directly referencing resource files is a method of direct coupling, which can cause file upgrade troubles, we can use an external method to solve this direct coupling (adding an attribute to FileVersion and changing the internal address to a CDN address ).

Back to Top enable Compression

Compression of response results is also a commonly used method for website optimization. Because the current browsers support compression, if the server can compress the response results, for users with slow network speeds, it will reduce the transmission time of a lot of networks. The final experience is that the webpage display speed is getting faster!

Although IIS6 provides the compression setting interface, the configuration is based on the server level:

Note: here the [application file] does not include aspx. to compress the aspx response, you must manually modify x: \ WINDOWS \ system32 \ inetsrv \ MetaBase. xml file (refer to the font size Section ):

""        ""        ""        ""        ""        ""        "        ""        ""        ""        "            axd"    

Note: To modify MetaBase. xml, you must stop the IIS Admin Service.

In IIS7, We can configure the compression parameters at the server level:

Enable or disable the compression function for each website:

Note: MetaBase. xml is no longer used in IIS7, so we cannot find the IIS6 settings. IIS7 compression filters do not apply to extensions, but use the mimeType rule (stored in applicationHost. config ). According to IIS7 compression rules, when dynamic compression is enabled, the aspx response results are compressed.

Differences between the two compression methods: 1. Static content compression: when the server first responds to a static file, it will generate a compressed result and save it to the disk for reuse. 2. Dynamic Content compression: [each time] compresses the response results in the memory before responding to the client, so it will put some burden on the CPU.

Note: If you want to enable dynamic content compression, You need to evaluate whether the server's CPU is sufficient (observe the task manager or view the performance counter ).

Return to the top to delete useless HttpModule

For a website, some HttpMoudle provided by ASP. NET may not be required. However,If you do not disable them manually, they will still run. For exampleMeThe following HttpMoudle will be disabled:

""""""""""

For websites that use Forms authentication, the following httpmodules can also be disabled:

""""
Back to Top other Optimization Options

Optimizing ASP. NET websites is a big topic. In addition to the methods described in the blog, you can also refer to the following methods: 1. Upgrade server hardware configuration. 2. Use Windows Server 2008 or a later version of the operating system (network performance is better than 2003 ). 3. Optimize the operating system configuration (for example, disable unnecessary services ). 4. Disable debugging mode. 5. The website uses a dedicated application pool.

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.