ASP. NET controls HTTP cache)

Source: Internet
Author: User
Tags website performance

Reading directory

    • Start
    • Normal HTTP Request Process
    • Cache page request process
    • Server programming for cache pages
    • What is a 304 response?
    • How to program 304 responses
    • How to avoid HTTP caching

In the previous blog [Detailed ASP. NET cache and its advanced usage], I introduced ASP. NET cache, a cache API used by the server. Develop an ASP. in the process of the Net website, there are actually many places where cache can be used, just because ASP. net is a server-based development platform. Naturally, we oftenCodeVarious cache technologies are used. HoweverProgramThe service object is the browser of the client. Generally, we cannot directly control the behavior of the browser. However, the browser can follow the instructions of the background website, use some optimization methods to render the page faster. The client browser also has its own caching mechanism. Generally, the browser uses caching to optimize page display. However, we cannot directly use C # code to control browser cache operations, however, we can tell the browser how to use the cache to optimize the website performance.

The topic of this blog is to use ASP. NET to control browser caching during HTTP requests.

Back to the top of the normal HTTP Request Process

Before introducing the HTTP request process of a browser, I think it is necessary to first look at the process of requesting a common ASPX page by the browser.
Note: This document describes the HTTP request process and uses Fiddler to analyze the specific request process in large quantities.

It is a request process for a common ASPX page. It is common because I did not perform any cache processing on the page after creating it.
The response status of the server is HTTP/1.1 200 OK, which indicates a successful response from the server.
In addition, pay attention to the cache response header in the image. The reason why the red line is framed is to remind you that the content of this section will change in the following sections, pay attention to comparing them at that time. In fact, the result is only the default value. It does not indicate that the page needs to be cached.

Request process back to the top cache page

Next let's take a look at the request process of a cache page:

Compared with the previous image, we can see that we now have three response headers, Max-age, expires, and last-modified.

The meanings of these three headers are as follows:
1. Max-age, expires: the meaning to be expressed is almost the same. Max-age indicates how many seconds the HTTP response results should be cached.
Expires indicates when the response result of an HTTP request should be cached and expire, which is a UTC time.
Another date header indicates the time when the htpp response was sent. We can find that date + max-age = expires
2. Last-modified: the server informs the client of the last modification time of the HTTP document returned in this response. This header is related to the implementation of 304, which will be explained later.

After analyzing the HTTP request process, let's take a look at what the server page looks like:

Note: The most critical line of code in the above Code is:

<%@OutputcacheDuration= "10"Varybyparam= "NONE"%>

The outputcache command is used to output the above response headers, which is used to tell the browser that the page needs to be cached for 10 seconds.

At this point, some people may wonder: When will cache pages play a role?
To demonstrate the practical significance of the cache page, I will click these links on the page to explain the page display in the form of a series of requests, and analyze the role of the cache based on the display results of the page.

Let's take a look at the display on this page:

The page is very simple, mainly displaying the page generation time and a Refresh link. From the Page code provided above, we should know that if the page is generated by the server, the current time will be displayed.

However, when I keep clicking [refresh this page], the page time does not change. When I find that the time has changed, the page is displayed as follows:

During the test, I opened fiddler all the time, and I also dropped the result of the request monitored by fiddler:

From Fiddler, I saw that Firefox only had two requests, but I clicked the [refresh this page] for at least 10 times.

All of the above is a fact:If the page needs to jump to a cache page and the cache page has not expired, the browser does not initiate a request to the server, but uses the cache page.

Summary: The benefits of page caching are: Before the cache page expires, the userClick the jump LinkSubsequent access will not be requested again. This can reduce the number of accesses to the server, so using this feature can improve program performance.

Server programming back to the top cache page

We have demonstrated the effect of the cache page generated by using the outputcache command. Because the commands need to be written to the page at the design stage of the page, they are not flexible enough and cannot be adjusted at runtime, although ASP. net also allows us to use cacheprofile to introduce definitions on the web. configuration in config, but the configuration is still not flexible when the code is running. Let's take a look at how to use the code to achieve the above effect.

In fact, using code to implement cache pages is also very simple, just like this:

Protected voidPage_load (ObjectSender,EventargsE) {response.Cache.Setcacheability (Httpcacheability.Public); Response.Cache.Setexpires (Datetime.Now.Addseconds (10.0));}

In fact, the key is to call response. cache.
Note: Response. cache is not the same as the cache mentioned in my previous article [describe ASP. NET cache and its advanced usage]. The two are completely irrelevant.
Response. cache provides: methods used to set the cache-specific HTTP header and to control the ASP. NET page output cache.

Let's talk about the sample code in the previous two paragraphs. Some may wonder if their final results will be consistent?

To answer this question, I think it is necessary to take a look at the final code running on the page using the outputcache command.

In the temporary compilation directory of ASP. NET, I found a version of the previous file processed by ASP. NET:

We can see that the page's settings for the outputcache command will eventually call the page class to define a method:

 
Protected internal virtual voidInitoutputcache (OutputcacheparametersCachesettings)

That method is too long, and the final processing method is still calling this. response. cache. If you are interested, you can check the method yourself. As for the reason why the parameter of this method is outputcacheparameters, I think this is easy to understand: it is convenient to include all the parameters of the outputcache command together.

Therefore, for this reason, we can also directly call response in the code. some cache methods are used to achieve the same effect. Because the code can adjust the cache policy according to various parameters during runtime, it is more flexible and can be simplified by inheriting the base class.

Note: If you use the outputcache command and use it with the outputcache module, you can achieve the effect of 304.

Back to Top what is 304 response?

Through the previous example, we have seen the benefits of Caching: it can be reduced to server access, because the page can be displayed without accessing the server, which for the server, this reduces access pressure.However, if you force refresh the browser, the browser ignores the cache page and directly initiates a request to the server.

That is to say, the cache page will be invalid when the user forces to refresh the browser.
However, we use the cache page because we want to tell the browser that the data will not change for a certain period of time, so we do not need to request the server again. However, we cannot block user behavior. Due to browser re-access, the original idea of cache will fail. The final result is that the page is re-executed on the server, and the generated HTML code will be re-sent to the client. The result of this refresh may also be meaningless, because the data may not change at all, so the page obtained cannot be changed.

Let's take a simple example: the client needs to browse an image. When a browser accesses an image for the first time, the browser certainly does not have any cache records. At this time, it accesses the server and the server returns the image content. However, because an image may be referenced by multiple pages, the possibility of modification is very small. Therefore, there is no need to read the image and return the image content for multiple requests from the same browser. This will not only affect performance but also waste bandwidth. Therefore, when server software such as IIS accesses such static files, some tags will be output in the response header to inform the browser that the file can be cached.

Back to the above-mentioned [user forced refresh] Question, what will IIS do at this time? See:

Note: Besides the HTTP status code 304,No data is returned.

To impress you with the 304 response, I captured an image response result with a status code of 200:

Through the comparison of the two images, we can see it clearly:304 and 200 are not only numerical differences, but are there any returned results.

If no result is returned, how does the Browser display it?
Do you have such doubts?
In fact, do not worry, the browser will use its cached version to display. That is to say: no matter how powerful the user is, the server does not return results, but it can still be displayed normally.

Obviously, this effect is what we want.
If you use this method, the cache page mentioned above has been badly refreshed by users.
However, I would like to remind you that the webdev.webserver.exe self-contained in Visual Studio does not support 304 responses, so you should not try it out without any results.

Back to Top how to program 304 responses

We have seen the effect of 304 responses. However, in ASP. net, the program we developed is a dynamic page, not an image. We hope that a page can be cached for a period of time in this way. I think this requirement may be more meaningful.

Next, I will demonstrate how to implement it through programming.
In the following example, the page displays the time generated by the page on the server. The time has changed, indicating that the page has been re-executed.

I think it doesn't make much sense to intercept a series of images. I just took a picture and showed it many times.

It reflects the process of multiple requests to An ASPX page. It can be seen from the image that only the first response is 200, followed by 304, which is the expected result.

Let's take a look at its implementation code:

 Public partial class  Demo304 : System . Web . UI .  Page {Protected void Page_load ( Object Sender, Eventargs E ){ Datetime DT; If ( Datetime  . Tryparse (Request . Headers [ "If-modified-since" ], Out DT )){ // Note: If it is within 20 seconds, I will respond in 304.  If ((Datetime  . Now - DT) . Totalseconds <  20.0 ) {Response . Statuscode =  304 ; Response . End (); Return ;}}// Pay attention to this call. It can generate the "Last-modified" response header. After the browser receives this header, // when it subsequently accesses this page, the time will be sent to the server in the form of "If-modified-since", so that the above Code can take effect. Response . Cache . Setlastmodified ( Datetime  . Now );}}

Although the Code is not complex, I plan to explain it as follows:
When the browser requests the page for the first time, it will execute the setlastmodified call. It will output a "last-modified" response header when the browser responds. Then, when the browser accesses the page again, theContentThe Request Header "If-modified-since" is sent to the server. In this case, the server can determine whether to use the 304 response based on the specific logic.

In the previous request image example, the server sends the last modification time of the image file to the browser as "last-modified". When the browser requests the image subsequently, the server is also notified in the form of "If-modified-since". At this time, the server only needs to check this image again to see if the image has been modified since the last access, of course, we will tell the browser in the form of 304: continue to use the Cache version.

In fact, the server also uses another pair of [Request/Response] headers:

The use of these two headers is: the server Outputs An etag header. After receiving the header, the browser sends it to the server in the form of IF-None-match in subsequent requests, for the server to determine whether to use the 304 response.

"Last-modified" and "etag" are both. In fact, you only need to use one of them. The key is to check how the server processes them. The browser only sends them again after receiving them.

However, the preceding sample code does not use a cache header. In fact, you can also use it to minimize access to the server. After all, the user will not always be able to use a browser. Although there are big differences between the two methods, they can definitely complement each other.

In order to visually depict the request process of cache pages (or other documents), I drew a picture for your reference:

How to avoid HTTP caching back to the top

The previous section describes two methods to use browser cache. However, sometimes the browser may wish to discard the cached results. Currently, browsers have cache functions, especially for some static files, such as images, JS, CSS, and HTML files. But sometimes we need to update CSS and JS files. If the browser still uses its cached version, it will obviously be a problem. In addition, some websites use URL rewriting to convert the original dynamic page extension to static html files. Therefore, we still hope that the browser will not cache these pseudo static pages in some cases.

At this point, we want the browser to discard the results obtained from the HTTP request. Generally, when a browser processes (as it thinks) static files, it will save the cached results according to the URL as the key. Therefore, the common solution is to modify the URL, for example: the original request is ABC. JS, to be changed to ABC. JS? T = 23434, followed by a parameter, so that the previous cache does not work. The value of parameter t can be manually specified based on the last modification time of the file. In short, you only need to change it.

However, for pseudo-static pages, we can no longer use this method, so there is no need to explain the reason.
Therefore, you can output a response header on the server to notify the browser of the Response Header. Do not cache this file. For example, you can call this method:

Response.Cache.Setnostore ();

It will generate such response header content:

 
Cache-control: private, no-store

Many browsers can recognize it. Another way is to set an expiration time.

The method of adding additional parameters in the URL mentioned above is also common in JS. For example, jquery supports making an Ajax request not cached. The method is to set {cache: false }, in the end, it will add a temporary parameter to the generated URL to ensure that the address of the subsequent request is not repeated, so as to avoid caching. Jquery is too simple to use, so I will not provide the sample code.

Click here to download the sample code

 

From: http://www.cnblogs.com/fish-li/archive/2012/01/11/2320027.html

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.