我编写了VirtualPathProvider的自定义实现,它允许我从Azure Blob Storage中提取图像。提供程序会做它的事情,但在每个对性能不利的请求时调用GetFile
。
获取文件
public override VirtualFile GetFile(string virtualPath)
{
string path = this.FormatVirtualPath(virtualPath);
if (!path.StartsWith(this.pathPrefix, StringComparison.InvariantCultureIgnoreCase))
{
return base.GetFile(virtualPath);
}
string fileSystemPath = this.RemovePathPrefix(path);
return new FileSystemVirtualFile(
virtualPath,
() =>
this.fileSystem.Value.OpenFile(fileSystemPath));
}
由于我知道 blob 的最后修改日期,我认为添加一些缓存是个好主意,但我似乎无法获得任何工作。
阅读它似乎我需要覆盖我所做的方法GetCacheDependency
和GetFileHash
,如下所示:
GetCacheDependency
public override CacheDependency GetCacheDependency(string virtualPath,
IEnumerable virtualPathDependencies,
DateTime utcStart)
{
string path = this.FormatVirtualPath(virtualPath);
if (!path.StartsWith(this.pathPrefix, StringComparison.InvariantCultureIgnoreCase))
{
return base.GetCacheDependency(virtualPath,
virtualPathDependencies,
utcStart);
}
return new BlobCacheDependency(
this.fileSystem
.Value.GetLastModified(path)
.DateTime.ToUniversalTime());
}
获取文件哈希
public override string GetFileHash(string virtualPath, IEnumerable virtualPathDependencies)
{
string path = this.FormatVirtualPath(virtualPath);
if (!path.StartsWith(this.pathPrefix, StringComparison.InvariantCultureIgnoreCase))
{
return base.GetFileHash(virtualPath, virtualPathDependencies);
}
byte[] bytes = Encoding.Unicode.GetBytes(virtualPath.ToCharArray());
using (MD5CryptoServiceProvider md5 = new MD5CryptoServiceProvider())
{
byte[] hash = md5.ComputeHash(bytes);
// Concatenate the hash bytes into one long String.
return hash.Aggregate(
new StringBuilder(32),
(sb, b) => sb.Append(b.ToString("X2",
CultureInfo.InvariantCulture)))
.ToString().ToLowerInvariant();
}
}
我还有一个自定义CacheDependency
实现。
public class BlobCacheDependency : CacheDependency
{
public BlobCacheDependency(DateTime lastModifiedUtc)
{
this.SetUtcLastModified(lastModifiedUtc);
}
}
不幸的是,在请求图像时,这些其他方法都不会被调用。我不确定缺少什么。有什么想法吗?
所以答案是在我的VirtualFile
实现中的Open()
方法中设置响应缓存。这允许浏览器缓存文件。
这有点笨拙,但有效。在我的代码中,它现在看起来像这样。
public override Stream Open()
{
// Set the response headers here. It's a bit hacky.
HttpCachePolicy cache = HttpContext.Current.Response.Cache;
cache.SetCacheability(HttpCacheability.Public);
cache.VaryByHeaders["Accept-Encoding"] = true;
IFileSystem azureBlobFileSystem = FileSystemProviderManager.Current.GetUnderlyingFileSystemProvider("media");
int maxDays = ((AzureBlobFileSystem)azureBlobFileSystem).FileSystem.MaxDays;
cache.SetExpires(DateTime.Now.ToUniversalTime().AddDays(maxDays));
cache.SetMaxAge(new TimeSpan(maxDays, 0, 0, 0));
cache.SetRevalidation(HttpCacheRevalidation.AllCaches);
return this.stream();
}
看
http://forums.asp.net/t/1745003.aspx?VirtualPathProvider+files+do+not+have+cache+control+headers