Http response: Last-Modified, ETag, and asp.net web api implementation

Source: Internet
Author: User
Tags http request microsoft iis

Basic knowledge
1) What is "Last-Modified "?
When the browser requests a URL for the first time, the server returns 200, and the content is the resource you requested, at the same time, there is a Last-Modified attribute to mark the Last modification time of this file on the service end. The format is similar to this:
Tue, 24 Apr 2012 13:53:56 GMT

When the client requests this URL for the second time, according to the HTTP protocol, the browser will send the If-Modified-Since header to the server, asking If the file has been Modified after the time:
If-Modified-Since: Tue, 24 Apr 2012 13:53:56 GMT

If the resources on the server are Not Changed, the HTTP 304 (Not Changed.) status code is automatically returned and the content is blank, which saves the amount of data transmitted. When the server code changes or the server is restarted, the resource is re-issued, and the returned result is similar to the first request. This ensures that resources are not repeatedly sent to the client, and that the client can obtain the latest resources when the server changes.
2) What is "Etag "?
The HTTP specification defines ETag as the object value of the requested variable ". In other words, ETag is a token that can be associated with Web resources ). A typical Web resource can be a Web page, but it may also be a JSON or XML document. The server is solely responsible for determining what the mark is and its meaning, and transmitting it to the client in the HTTP response header. The following is the format returned by the server:
"9077da2dec72bbb7151a6579fa214de0"

The query update format of the client is as follows:
"9077da2dec72bbb7151a6579fa214de0"

If ETag does not change, status 304 is returned and no result is returned, which is the same as Last-Modified.

How does Last-Modified and Etags help improve performance?
Smart developers will use the http header of the Last-Modified and ETags requests together, so that the cache of the client (such as the browser) can be used. Because the server first generates the Last-Modified/Etag mark, the server can use it later to determine whether the page has been Modified. Essentially, the client sends this mark back to the server and requires the server to verify its (client) cache.

The process is as follows:
1. The client requests A page ().

2. The server returns to page A and adds A Last-Modified/ETag to page.

3. The client displays the page and caches the page together with Last-Modified/ETag.

4. The customer requests page A again and passes the Last-Modified/ETag returned by the server in the Last request to the server.

5. The server checks the Last-Modified or ETag and determines that the page has not been Modified since the Last client request. The server returns the response 304 and an empty response body.

Correct use of Etag and Expires identification can make the page Cache more effective.
When the client sends a Request for a URL for the first time through a browser, the browser will send the Header (HTTP Request Header) to the server according to the Http protocol ), when the server responds with the Http Reponse Header, the server returns 200 in the following format:

HTTP/1.1 200 OK
Cache-Control: public, max-age = 1728000
Transfer-Encoding: chunked
Content-Type: image/jpeg
Expires: Sun, 20 May 2012 16:26:22 GMT
Last-Modified: Tue, 24 Apr 2012 13:53:56 GMT
ETag: "9077da2dec72bbb7151a6579fa214de0"
Server: Microsoft-Microsoft IIS/7.5
X-AspNet-Version: 4.0.30319
X-Powered-By: ASP. NET
Date: Mon, 30 Apr 2012 16:26:22 GMT

When the client requests this URL for the second time, according to the HTTP protocol, the browser will send an Http Request Header to the server. The server responds and records that the relevant record property tag file has not been changed, the server returns 304, which is directly read from the cache:

HTTP/1.1 304 Not Modified
Cache-Control: no-cache
Pragma: no-cache
Expires:-1
Server: Microsoft-Microsoft IIS/7.5
X-AspNet-Version: 4.0.30319
X-Powered-By: ASP. NET
Date: Mon, 30 Apr 2012 16:30:06 GMT

 

The implementation code of asp.net web api is as follows:

The code is as follows: Copy code

// GET/img/2012031023134242.png
[HttpGet]
Public HttpResponseMessage Get ([FromUri] string filename)
        {
HttpResponseMessage response = new HttpResponseMessage ();

Export fsdirectory fs = new export fsdirectory (new export fsdirectoryparameters () {ConnectionString = this. ConnectionString });
Repeated gridfsfileinfo fileInfo = fs. GetFileInfo (filename );
If (fileInfo = null)
            {
Throw new HttpResponseException ("The file does not exist.", HttpStatusCode. NotFound );
            }
String etag = string. Format ("" {0} "", fileInfo. MD5 );
Var tag = Request. Headers. IfNoneMatch. FirstOrDefault ();
If (Request. Headers. IfModifiedSince. HasValue & tag! = Null & tag. Tag = etag)
            {
Response. StatusCode = HttpStatusCode. NotModified;
            }
Else
            {
MemoryStream responseStream = new MemoryStream ();
Repeated gridfsstream gfs = fileInfo. OpenRead ();

Bool fullContent = true;
If (this. Request. Headers. Range! = Null)
                {
FullContent = false;
// Currently we only support a single range.
RangeItemHeaderValue range = this. Request. Headers. Range. Ranges. First ();

// From specified, so seek to the requested position.
If (range. From! = Null)
                    {
Gfs. Seek (range. From. Value, SeekOrigin. Begin );

// In this case, actually the complete file will be returned.
If (range. From = 0 & (range. To = null | range. To> = gfs. Length ))
                        {
Gfs. CopyTo (responseStream );
FullContent = true;
                        }
                    }
If (range.! = Null)
                    {
// 10-20, return the range.
If (range. From! = Null)
                        {
Long? RangeLength = range. To-range. From;
Int length = (int) Math. Min (rangeLength. Value, gfs. Length-range. From. Value );
Byte [] buffer = new byte [length];
Gfs. Read (buffer, 0, length );
ResponseStream. Write (buffer, 0, length );
                        }
//-20, return the bytes from beginning to the specified value.
Else
                        {
Int length = (int) Math. Min (range. To. Value, gfs. Length );
Byte [] buffer = new byte [length];
Gfs. Read (buffer, 0, length );
ResponseStream. Write (buffer, 0, length );
                        }
                    }
// No Range.
Else
                    {
// 10-, return from the specified value to the end of file.
If (range. From! = Null)
                        {
If (range. From <gfs. Length)
                            {
Int length = (int) (gfs. Length-range. From. Value );
Byte [] buffer = new byte [length];
Gfs. Read (buffer, 0, length );
ResponseStream. Write (buffer, 0, length );
                            }
                        }
                    }
                }
// No Range header. Return the complete file.
Else
                {
Gfs. CopyTo (responseStream );
                }
Gfs. Close ();
ResponseStream. Position = 0;
Response. StatusCode = fullContent? HttpStatusCode. OK: HttpStatusCode. PartialContent;
Response. Content = new StreamContent (responseStream );
Response. Content. Headers. ContentType = new MediaTypeHeaderValue (fileInfo. ContentType );
Response. Headers. ETag = new EntityTagHeaderValue (etag );
Response. Headers. CacheControl = new CacheControlHeaderValue ();
Response. Headers. CacheControl. Public = true;
Response. Headers. CacheControl. MaxAge = TimeSpan. FromHours (480 );
Response. Content. Headers. Expires = DateTimeOffset. Now. AddDays (20 );
Response. Content. Headers. LastModified = fileInfo. UploadDate;
            }
Return response;

        }

Refer:

Sample message handler for managing etags in web api

Http://codepaste.net/4w6c6i

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.