Fork me on GitHub

http响应Last-Modified和ETag以及asp.net web api实现

基础知识
1) 什么是”Last-Modified”?
在浏览器第一次请求某一个URL时,服务器端的返回状态会是200,内容是你请求的资源,同时有一个Last-Modified的属性标记此文件在服务期端最后被修改的时间,格式类似这样:
Tue, 24 Apr 2012 13:53:56 GMT

客户端第二次请求此URL时,根据 HTTP 协议的规定,浏览器会向服务器传送 If-Modified-Since 报头,询问该时间之后文件是否有被修改过:
If-Modified-Since: Tue, 24 Apr 2012 13:53:56 GMT

如果服务器端的资源没有变化,则自动返回 HTTP 304 (Not Changed.)状态码,内容为空,这样就节省了传输数据量。当服务器端代码发生改变或者重启服务器时,则重新发出资源,返回和第一次请求时类似。从而保证不向客户端重复发出资源,也保证当服务器有变化时,客户端能够得到最新的资源。
2) 什么是”Etag”?
HTTP 协议规格说明定义ETag为“被请求变量的实体值” 。 另一种说法是,ETag是一个可以与Web资源关联的记号(token)。典型的Web资源可以一个Web页,但也可能是JSON或XML文档。服务器单独负责判断记号是什么及其含义,并在HTTP响应头中将其传送到客户端,以下是服务器端返回的格式:
"9077da2dec72bbb7151a6579fa214de0"

客户端的查询更新格式是这样的:
"9077da2dec72bbb7151a6579fa214de0"

如果ETag没改变,则返回状态304然后不返回,这也和Last-Modified一样。

Last-Modified和Etags如何帮助提高性能?
聪明的开发者会把Last-Modified 和ETags请求的http报头一起使用,这样可利用客户端(例如浏览器)的缓存。因为服务器首先产生 Last-Modified/Etag标记,服务器可在稍后使用它来判断页面是否已经被修改。本质上,客户端通过将该记号传回服务器要求服务器验证其(客户端)缓存。

过程如下:
1,客户端请求一个页面(A)。

2,服务器返回页面A,并在给A加上一个Last-Modified/ETag。

3,客户端展现该页面,并将页面连同Last-Modified/ETag一起缓存。

4,客户再次请求页面A,并将上次请求时服务器返回的Last-Modified/ETag一起传递给服务器。

5,服务器检查该Last-Modified或ETag,并判断出该页面自上次客户端请求之后还未被修改,直接返回响应304和一个空的响应体。

正确使用Etag和Expires标识处理,可以使得页面更加有效被Cache。
在客户端通过浏览器发出第一次请求某一个URL时,根据 HTTP 协议的规定,浏览器会向服务器传送报头(Http Request Header),服务器端响应同时记录相关属性标记(Http Reponse Header),服务器端的返回状态会是200,格式类似如下:

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-IIS/7.5
X-AspNet-Version: 4.0.30319
X-Powered-By: ASP.NET
Date: Mon, 30 Apr 2012 16:26:22 GMT

客户端第二次请求此URL时,根据 HTTP 协议的规定,浏览器会向服务器传送报头(Http Request Header),服务器端响应并记录相关记录属性标记文件没有发生改动,服务器端返回304,直接从缓存中读取:

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

 

asp.net web api的实现代码如下:

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

            MongoFSDirectory fs = new MongoFSDirectory(new MongoFSDirectoryParameters() { ConnectionString = this.ConnectionString });
            MongoGridFSFileInfo 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();
                MongoGridFSStream 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.To != 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.To
                    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;

        }

参考:

sample message handler for managing etags in web api

http://codepaste.net/4w6c6i

posted @ 2012-05-01 00:45  张善友  阅读(6789)  评论(10编辑  收藏  举报