elaborate on ASP. NET control HTTP cache [GO]

Source: Internet
Author: User

Read Catalogue

    • Begin
    • The normal HTTP request process
    • Request process for cached pages
    • Server-side programming for cached pages
    • What is 304 answer?
    • How to implement 304 response programmatically
    • How to avoid HTTP caching

In the previous blog, "About ASP. NET cache and its advanced usage," I showed you the ASP. NET cache, the caching API used by this server side. In the process of developing an ASP, there are many places where we can use caching, but since ASP. NET is a server-based development platform, naturally we often use various caching techniques in the server's code, however, Because the Web application's service object is the client's browser, in general, we do not directly control the behavior of the browser, but the browser can be based on the background of the site's instructions, to take some optimizations to render the page more quickly. The client browser also has its own caching mechanism, usually the browser also uses the cache to optimize the display of some pages, but we can not directly use C # code to control the browser's caching operations, but we could tell the browser how to use the cache, so as to optimize the performance of the site.

The topic of this blog is: Use ASP. NET to control some methods of browser caching during HTTP requests.

Back to the top of normal HTTP request process

Before I start introducing the browser to the HTTP request process, I think it's important to take a look at the process of requesting a normal ASPX page from the browser.
Description: This article uses Fiddler to analyze the specific request process as it describes the HTTP request process.

is a normal ASPX page request process, saying that it is normal because: after I created this page, it does not do any caching aspects of processing.
In the picture we can see that the response status of the server is: http/1.1 OK, this is a flag for a successful server response.
In addition, to note the cache in the image of the response header section, I came out of the red box, I would like to remind you that this piece of content will be changed in the following sections, please pay attention to compare them. And the situation here is actually just the default value, it does not mean that this page needs to be cached.

Back to the top cache page request process

Here's another look at the request process for a cached page:

As you can see from the previous picture, there are now more than three response headers for "Max-age", "Expires" and "last-modified".

The meanings of these three heads are as follows:
1. Max-age,expires: The meaning of the expression is basically the same. Max-age indicates how many seconds the response of an HTTP should be cached.
The expires is that the response of an HTTP should be cached to what time it expires, which is a UTC time.
Another date header indicates the time that the HTPP response was emitted, and we can see that date + Max-age = Expires
2. Last-modified: The server tells the client the last modification time of the HTTP document returned by this response. This head is related to the realization of 304, which is explained later.

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

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

<%Durationvarybyparam%>  

It is because of the use of this outputcache instruction that the last few response headers are output to tell the browser that this page needs to be cached for 10 seconds.

When it comes to this, some people may wonder: when does a cached page work?
In order to demonstrate the practical significance of caching pages, I will click on these links in the page to illustrate how the page is displayed during a series of requests, and analyze the role of the cache with the results of the page's display.

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

The page is very simple, mainly shows the page generation time and a refresh link. From the page code provided above, we should be able to know if this page is generated by the server, the current time will be displayed.

However, when I have been (frequently) clicking on the "Refresh this page" link, the time of the page has not changed, and when I find that the time has changed, the page has been shown this way:

As a result of the testing process, I have been opening the fiddler, just as I have fiddler to monitor the request results down:

From fiddler, I saw that Firefox actually had only two requests, but I clicked on that "refresh this page" at least 10 times.

All of this, just a fact: if the page needs to jump to a cached page, and that cached page has not expired, then the browser does not initiate a request to the server, but instead uses the cached page.

Summary: The benefit of page caching is that the cached page will not request the server again until it expires, and the user clicks on the subsequent access that was raised by the jump link . This can reduce the number of accesses to the server, so using this feature can improve program performance well.

Back to top cache page for server programming

The effect of caching pages produced by using the OutputCache directive is shown earlier, because those instructions need to be written on the page at the design stage of the page, so they are not flexible enough to be adjusted at run time. While ASP. NET also allows us to use CacheProfile to introduce the configuration defined in Web. config, the configuration is not as flexible as running code. Let's take a look at how to use the code to achieve the above effect.

Actually using the code to implement the cache page is also very simple, just need to do so:

protected void Page_Load (EventArgs e) {    Response. Cache. SetCacheability (httpcacheability. public); Response. Cache. SetExpires (DateTime. Now. AddSeconds (10.0));}          

In fact, the key is the call to Response.Cache.
Note: Response.Cache is not the same as the one that I said in the blog "about the ASP. NET cache and its advanced usage", which is completely irrelevant.
Response.Cache provides methods for setting cache-specific HTTP headers and for controlling the output cache of an ASP.

Let's still say the previous two-paragraph example code. May some people think that the end result will really be the same?

To answer this question, I think it's necessary to look at what the code in the previous page of the OutputCache command would look like in the final run.

In the ad-hoc compilation Directory of ASP, I found an ASP-processed version of the previous file:

We can see that the page is set for the OutputCache directive and will eventually call the page class to define a method:

protected internal virtual void InitOutputCache (outputcacheparameters cachesettings)

That method is too long, and the final processing method is to call this. Response.Cache, be interested to see the method yourself. As to why the parameter of this method is outputcacheparameters, I think this is easy to understand: it is convenient to pass all the parameters of the outputcache instruction together.

So, for this reason, we can also call Response.Cache's methods directly in the code to achieve the same effect, because the code can adjust the cache policy at run time according to various parameters, so it will be more flexible, and can use the inheritance of the base class to simplify the implementation.

Note: If you use the outputcache instruction with the OutputCache module, you can achieve a 304 effect.

Back to top what is 304 answer?

From the previous example, we have seen the benefits of caching: it is possible to reduce access to the server, because the server can display the page, which for the server, can alleviate some of the access pressure. However, if the user forces the browser to refresh, the browser will ignore the cached page and re-initiate the request directly to the server.

That is, the cached page is not valid when the user forces the browser to refresh.
However, we use cached pages because we want to tell the browser that the data does not change for a certain amount of time, so there is no need to request the server again. However, we cannot prevent users from behaving. Because of the browser re-visit, we originally conceived the idea of caching will be frustrated, the final result is: The page is re-executed in the server, the resulting HTML code will be sent back to the client. The result of this re-refresh may also be meaningless, because the data may not have changed at all, so the resulting page is not likely to change.

Let me give you a simple example: The client wants to browse for a picture. When the browser first to access the picture, the browser must not have any of its cache record, at this time it to access the server, the server also returned the contents of the picture. However, since a picture may be referenced by multiple pages, the likelihood of its being modified is very small. Therefore, it is not necessary to read the picture and return the contents of the picture for multiple requests from the same browser, which both affect performance and waste bandwidth. As a result, server software such as IIS, for such static file access, will output some tags on the response header, to tell the browser of this file you can cache it up.

Or go back to the "user forced refresh" issue that was mentioned earlier, what happens to IIS now? Please see:

Note that no data is returned except that the HTTP status code becomes 304.

To give you a deep impression of the 304 response, I intercepted a picture with a status code of 200 responding to the result:

Through the comparison of these two pictures, now see clearly:304 and 200 is not only the difference between the numbers, the most important difference is whether there is no return results.

No results returned, how should the browser be displayed?
Do you have any doubts about that?
Don't worry, the browser will use its cached version to display it. In other words: no matter how the user forced the brush, the server will not return the results, but still can display normally.

Obviously, this effect is what we want.
The above mentioned cache page is the user's strong brush problem, if this method, it is more perfect.
However, one thing I would like to remind you is that the WebDev.WebServer.exe that comes with Visual Studio does not support 304 responses, so you should not experiment with it, and there will be no results.

Back to top how to programmatically implement 304 responses

We saw the effect of 304 response in the front. However, in ASP. NET, we develop a program that is a dynamic page, not a picture, we prefer a page to be cached in this way for a period of time, I think this need may be more meaningful.

Below, I'll show you how to implement it programmatically.
In the next example, the page is displayed in the same sample, showing the time the page was generated on the server, and the time changed, indicating that the page was re-executed.

To re-intercept a series of pictures, I think the meaning is not big, I cut a picture to show the process of several strong brushes

Reflecting the process of requesting an ASPX page several times, as you can see from the picture, only the first response is 200, followed by a total of 304, which is the result you expect.

Let's take a look at its implementation code:

Although the code is not complicated, I would like to explain:
When the browser requests the page for the first time, it executes the setlastmodified call, which outputs a "last-modified" response header in response, and then, when the browser accesses the page again, the "last-modified" header obtained from the last request content , in the form of "if-modified-since" This request header to the service side, the server can be based on the specific logic to determine whether to use the 304 answer.

In the previous sample request picture, the server as the last modification time of the picture file as "last-modified" to the browser, the browser in the subsequent request that picture, and "if-modified-since" in the form of the service side, At this time, the service side just check this picture again to know whether the image after the last visit has changed, if not modified, of course, in the form of 304 of the browser: continue to use the cached version.

Or an example of a previous request picture, in fact the server also uses another pair of "request/Response" headers:

The use of these two headers is: The server output an ETag header, the browser after receiving, in the form of If-none-match in subsequent requests sent to the server, for the service side to determine whether to use 304 response.

"Last-modified" and "ETag" both, in fact, only need to use one is enough, the key is to see how the server handles them, the browser just after receiving, the next time to send out.

However, the preceding example code does not use the cache header, in fact, it can also be taken, so as to minimize access to the server, after all, the user does not always strong browser. Although there are big differences in these two ways, they are absolutely complementary.

In order to be able to portray the request process of caching pages (or other documents), I drew a picture for your reference:

Back to top how to avoid HTTP caching

In the previous section, there are two ways to use the browser's cache. But sometimes you might want the browser to discard its cached results. Now the browser has a cache function, especially for some static files, such as: Pictures, js,css, HTML files, can be cached. But sometimes we need to update the CSS, JS file, if the browser also use its cached version, obviously there is a problem. Some sites use URL rewriting to make the original dynamic page extension a static HTML file, so you still want the browser to not cache these pseudo-static pages at some point.

At this point, we want the browser to discard the results obtained from the HTTP request. In general, the browser in the processing (it considers) static files, will follow the URL as key to save those cached results, so the usual solution is to modify the URL, such as: The original request abc.js, to change to abc.js?t=23434, followed by a parameter, Let the previous cache not work. The value of the parameter T can be specified according to the last modification time of the file or manually, as long as you change it.

However, for pseudo-static pages, we can no longer use this method, why not explain it.
Then, you can use the server to output a response header, the response header to the browser, do not cache this file. For example, this method can be called:

Response. Cache. Setnostore (); 

It generates such a response header content:

Cache-control:private, No-store

Many browsers can recognize it. There is another way to set an expired expiration time.

The previous practice of adding extra parameters to URLs is more commonly used in JS, such as jquery, which allows an AJAX request not to be cached, by setting {Cache:false} and eventually adding a temporary parameter to the generated URL. To ensure that the address of the subsequent request is not duplicated, the goal of avoiding caching is eventually achieved. The use of jquery is so simple that I'm not going to show you an example code anymore.

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

elaborate on ASP. NET control HTTP cache [GO]

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.