Search code examples
cachingazurecdncache-controlvirtualpathprovider

Maintaining cache control property on a file when it is returned as Stream from VirtualPathProvider


I have implemented a VirtualPathProvider to return Theme files (images,css) for an Azure web site from the Azure CDN. It is working fine apart from one thing: the files that are coming from the CDN all have their cache control property set to "private" and so are never cached.

The actual blobs have their properties set correctly and if I access one by it's direct URL (i.e. not through the VPP) then the cache control is correct.

The problem seems to be in the Open() method of the VirtualFile class I have to implement to return the file as a Stream?

public override Stream Open()
    {
        CloudBlobClient client = new CloudBlobClient(cdnURL);
        CloudBlob blob = client.GetBlobReference(blobURL);
        blob.FetchAttributes();
        MemoryStream stream = new MemoryStream();
        BlobRequestOptions options = new BlobRequestOptions();
        options.BlobListingDetails = BlobListingDetails.Metadata;
        blob.DownloadToStream(stream,options);
        stream.Seek(0, SeekOrigin.Begin);
        return stream;
    }

Searching on this and I find most people have the problem the other way - i.e. files are cached when they don't want them to be. However none of the examples I can find are referencing a file from another URL. They all seem to use databases or just different physical paths.


Solution

  • Thanks to this answer on the asp.net forum http://forums.asp.net/post/4716700.aspx

    I have resolved the issue by adding in my Open() method:

    HttpContext.Current.Response.Cache.SetCacheability(HttpCacheability.Public);
    HttpContext.Current.Response.Cache.AppendCacheExtension("max-age=86400");