【问题标题】:ASP.net eTag cache thumbnail images on load/refresh加载/刷新时 ASP.net eTag 缓存缩略图
【发布时间】:2021-12-11 23:42:11
【问题描述】:

嘿,我一直在努力让我的 20 多个缩略图进入缓存状态,因此每次加载/重新加载页面时它并不总是让服务器获取图像。

我已经在我的响应调用中实现了“eTag”,如下所示:

var uriFetcher = new UriFetcher(fileUri);
var tempPath = uriFetcher.FetchFile();
var mime = MimeType(tempPath);

//displays like: xxxxxx_xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx.png
//This is the image file name. These names do not change.
string theETag = tempPath.Split('\\').Last();

context.Response.Cache.SetCacheability(HttpCacheability.Public);
context.Response.Cache.SetLastModified(DateTime.Now);
context.Response.Cache.SetValidUntilExpires(true);
context.Response.Cache.SetExpires(DateTime.Now.AddYears(1));
context.Response.Cache.SetMaxAge(new TimeSpan(1, 0, 0));
context.Response.CacheControl = "private";
context.Response.ContentType = mime;

//Add current image file name to the eTag
context.Response.AddHeader("ETag", "\"" + theETag + "\"");

var disposition = new ContentDisposition
{
    FileName = Path.GetFileName(tempPath),
    Inline = mime.Contains("image")
};

context.Response.AddHeader("content-disposition", disposition.ToString());

try {
   context.Response.TransmitFile(tempPath);
} catch {
   context.Response.TransmitFile(errorUri);
}

现在,在上面的 .cs 部分之后,它转到一个使用 jQuery 框架的 JavaScript 函数,以便将其放置到页面上供用户查看:

var imgThumbnail = img('thumbnail', '/' + thumbnailId + '/Thumbnail', preload)
    .tipsy({
        html: true,
        assetMode: false,
        fallback: assetData.Tooltip.html(),
        gravity: ($container.closest('#Side').length == 0) ? $.fn.tipsy.auto : 'e',
        topOffset: topOffset
    });
if (assetData.ProcessingRollupStatus != null) {
    if (assetData.ProcessingRollupStatus === 'Processing') {
        imgThumbnail.addClass('processing-status-processing');
    } else if (assetData.ProcessingRollupStatus === 'Waiting') {
        imgThumbnail.addClass('processing-status-waiting');
    }
}

$container
    .addClass('asset-item')
    .data('AssetData', assetData)
    .attr('id', assetData.Id)
    .append(imgThumbnail);

Firefox 的输出是这样的:

所以我遇到问题的部分是当我在页面加载/刷新时检查 eTag。我不确定我应该将该代码放在什么(或放在哪里)以便它加载图像(如果它们已经在缓存中)?

我在想这样的事情:

var requestedETag = context.Request.Headers["If-None-Match"];

if (requestedETag == last)
{
    return new HttpStatusCodeResult(HttpStatusCode.NotModified);
    //context.Result = new StatusCodeResult(304);
} else {
   ...........

那么,有人愿意告诉我如何进行这项检查吗?

【问题讨论】:

    标签: c# jquery asp.net caching etag


    【解决方案1】:

    我相信我找到了正确的方法:

    var uriFetcher    = new UriFetcher(fileUri);
    var tempPath      = uriFetcher.FetchFile();
    var mime          = MimeType(tempPath);
    string imgName    = tempPath.Split('\\').Last();
    var requestedETag = context.Request.Headers["If-None-Match"];
    
    if (requestedETag != imgName && requestedETag != null)
    {
        context.Response.StatusCode = 304;
        context.Response.StatusDescription = "Not Modified";
    }
    else
    {
       var disposition = new ContentDisposition
       {
           FileName = Path.GetFileName(tempPath),
           Inline   = mime.Contains("image")
       };
    
       context.Response.Cache.SetCacheability(HttpCacheability.ServerAndPrivate);
       context.Response.Cache.SetLastModified(DateTime.Now);
       context.Response.Cache.SetValidUntilExpires(true);
       context.Response.Cache.SetExpires(DateTime.Now.AddYears(1));
       context.Response.Cache.SetMaxAge(new TimeSpan(1, 0, 0));
       context.Response.CacheControl = "private";
       context.Response.ContentType = mime;
       context.Response.AddHeader("ETag", "\"" + imgName + "\"");
       context.Response.AddHeader("content-disposition", disposition.ToString());
    
       try
       {
          context.Response.TransmitFile(tempPath);
       }
       catch
       {
          context.Response.TransmitFile(errorUri);
       }
    }
    

    在特定页面的首次加载中,它定义了 eTag,即图像具有的唯一名称 (imgName)。 唯一的图像名称类似于 iAmAnImage123.png 作为示例

    如果用户刷新页面,则进入“If-None-Match”检查,检查具有唯一图像名称。这是与正在加载的当前图像 eTag 名称比较

    我的情况,每次用户加载/刷新页面时,我都会加载 1 MB

    最初只有 1 MB,然后只有 158.80 KB。节省了 835.80 KB!:

    所以基本上在上面的 If 语句中看起来像这样:

     |-> Question: Hey has iAmAnImage123.png already been loaded before? 
      |-> Yes: Well then, skip it and pass a 304 to the browser to let them know that
               its already been cached then go on to the next image. 
      |-> No: Alright, lets load it and then remember it by adding a unique eTag to
              it which we will be calling it iAmAImage123.png.
    

    【讨论】:

      猜你喜欢
      • 2011-06-16
      • 1970-01-01
      • 2015-06-20
      • 2016-08-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-02-13
      相关资源
      最近更新 更多