Based on the asp.net browser cache, this article provides the simplest method to prohibit the browser from caching to asp.net to implement browser caching and high-performance mvc browser caching and compression, if you need it, check it out.
Disable browser caching
The method is also very simple, that is, the output date is smaller than the current date, so as to simply implement the ASP. NET function to prohibit browser cache.
The Code is as follows: |
Copy code |
System. Web. HttpContext. Current. Response. BufferOutput = false; System. Web. HttpContext. Current. Response. ExpiresAbsolute = DateTime. Now. AddDays (-1 ); System. Web. HttpContext. Current. Response. Cache. SetExpires (DateTime. Now. AddDays (-1 )); System. Web. HttpContext. Current. Response. Expires = 0; System. Web. HttpContext. Current. Response. CacheControl = "no-cache "; System. Web. HttpContext. Current. Response. Cache. SetNoStore (); |
Implementation of asp.net browser cache
The above is the case of static pages, so what is the situation of aspx pages, that is, dynamic pages? Now, let's create a dynamic web page. First, create a simple aspx, as shown below:
The Code is as follows: |
Copy code |
<Body> <% = DateTime. Now %> </Body> |
Request the following header information:
Then we made multiple requests, and we found that every time it was OK, and we found that a very important information was lost in the header information, that is, Last-Modified. The server did not tell the browser the last modification date of its own object, so the browser had to go to the server to retrieve all the data each time. Here, we should understand that to prevent the browser from getting data, the dynamic program has to try to add the header information by itself.
Okay. Now we can add the simplest header information in the background code of ASPX:
The Code is as follows: |
Copy code |
Protected void Page_Load (object sender, EventArgs e) { This. Response. AddHeader ("Last-Modified", DateTime. Now. ToString ("U", DateTimeFormatInfo. InvariantInfo )); } |
After adding the header information, we find that after the URL is requested again, the header information becomes as follows:
The response header contains Last-Modified, and the request header contains If-Modified-Since.
Of course, we still find that each request is still 200OK. This is of course. Since the header information is added by ASP. NET in the background, we have to write the response status to the server. Now, let's assume that we want to cache the browser for 10 seconds. The complete code should be as follows:
The Code is as follows: |
Copy code |
Protected void Page_Load (object sender, EventArgs e) { This. Response. AddHeader ("Last-Modified", DateTime. Now. ToString ("U", DateTimeFormatInfo. InvariantInfo )); DateTime IfModifiedSince; If (DateTime. TryParse (this. Request. Headers. Get ("If-Modified-Since"), out IfModifiedSince )) { If (DateTime. Now-IfModifiedSince. AddHours (8). Seconds <10) { Response. Status = "304 Not Modified "; Response. StatusCode = 304; Return; } } // Others }
|
After this modification, If we continuously request this aspx page within 10 seconds, the system will always return the 304 status, that is, the browser will not get the body from the server, it will only read its own cache locally, so that the pressure on the server is naturally less. If we do not request this page from the server within 10 seconds, then OK will be returned in 10 seconds, that is, the page data will be retrieved from the server again.
Now, we use AB to simulate 100 concurrent users for 1000 requests. The comparison result is as follows (Note: To enhance the effect, we need to simulate some time-consuming actions in the background, for example, read the database ):
The left side is the aspx page that has not been cached, and the right side is the cache aspx page. We can see that the throughput is 10 times different.
Tip: when using AB for stress testing, add the If-Modified-Since Header information. The command is as follows:
Implementation of asp.net mvc browser cache and Compression
Cache plays a vital role in developing highly scalable web applications. We can cache any get request to the browser at a specified time, if the user requests the same URL within the specified time, the response will be implemented through the browser cache instead of the server. The following action filter can be used to implement the same functions in ASP. net mvc applications:
The Code is as follows: |
Copy code |
Using System; Using System. Web; Using System. Web. Mvc; Public class CacheFilterAttribute: ActionFilterAttribute { /// <Summary> /// Get or sets the cache duration in seconds. the default is 10 seconds /// </Summary> /// <Value> the cache duration in seconds </value> Public int Duration { Get; Set; } Public CacheFilterAttribute () { Duration = 10; } Public override void OnActionExecuted (FiterExecutedContext filterContext) { If (Duration <= 0) return; HttpCachePolicy cache = fiterContext. HttpContext. Response. Cache; TimeSpan cacheDuration = TimeSpan. FromSeconds (Duration ); Cache. SetCacheability (Httpcacheablity. public ); Cache. SetExpires (DateTime. Now. Add (cacheDuration ); Cache. SetMaxAge (cacheDuration ); Cache. AppendCacheExtension ("must revalidate, proxy-revalidate "); } } |
You can apply this filter in controller action method:
The Code is as follows: |
Copy code |
[CacheFilter (Duration = 60)] Public void Category (string name, int? Page) { } |
Compression is another important factor to improve the performance of web applications. Currently, most browsers accept compressed content, which greatly saves bandwidth. You can use the following filter to compress your response in ASP. net web applications:
The Code is as follows: |
Copy code |
Using System. Web; Using System. Web. Mvc; Public class CompressFilter: ActionFilterAttribute { Public override OnActionExecuting (FilterExecutingContext filterContext) { HttpRequestBase request = filterContext. HttpContext. Request; String acceptEncoding = request. Headers ("Accept-Encoding "); If (string. IsNullOrEmpty (acceptEncoding) return; AcceptEncoding = acceptEncoding. ToUpperInvariant (); HttpResponseBase response = filterContext. HttpContext. Response; If (acceptEncoding. Contains ("GZIP ")) { Reponse. AppendHeader ("Content-encoding", "gzip "); Response. Filter = new GZipStream (response. Filter, CompressionMode. Compress ); } } } |
You can apply this filter in Controller action method:
The Code is as follows: |
Copy code |
[CompressFilter] Public void Category (string name, int? Page) { } |
Of course, two filters can also be used together:
The Code is as follows: |
Copy code |
[CompressFilter] [CacheFilter (Duration = 60, Order = 2)] Public void Category (string name, int? Page) { } |