Making the Silverlight XAP file expire from browser cache programmatically

Viewed 16988

How to do I prevent a Silverlight XAP file being cached by the web browser?

The reason I want to do this is during development I don't want to manually clear the browser cache, I'm looking for a programmatic approach server side.

7 Answers

Using IIS management add a custom header Cache-Control with the value no-cache. That'll cause the browser to check that any cached version of the XAP is the latest before using it.

Add a query parameter to the URL for the XAP in the element on the HTML Page:

  • clientBin/MyApp.xap?rev=1
  • clientBin/MyApp.xap?rev=2

It will be ignored and break the cache. In IE8, there are some cache management tools: Open the Developer tools:

  • Try Cache...Always Refresh from Server
  • Try Cache...Clear Browser Cache for this domain...

Create a custom http handler for handling *.xap files and then set your caching options inside the handler.

Something like this...

using System;
using System.IO;
using System.Web;

public class FileCacheHandler : IHttpHandler
{
    public virtual void ProcessRequest(HttpContext context)
    {
        if (File.Exists(context.Request.PhysicalPath))
        {
            DateTime lastWriteTime = File.GetLastWriteTime(filePath);
            DateTime? modifiedSinceHeader = GetModifiedSinceHeader(context.Request);

            if (modifiedSinceHeader == null || lastWriteTime > modifiedSinceHeader)
            {
                context.Response.AddFileDependency(filePath);
                context.Response.Cache.SetLastModifiedFromFileDependencies();
                context.Response.Cache.SetCacheability(HttpCacheability.Public);
                context.Response.TransmitFile(filePath);
                context.Response.StatusCode = 200;
                context.Response.ContentType = "application/x-silverlight-app";
                context.Response.OutputStream.Flush();
            }
            else
            {
                context.Response.StatusCode = 304;
            }
        }
    }

    public DateTime? GetModifiedSinceHeader(HttpRequest request)
    {
        string modifiedSinceHeader = request.Headers["If-Modified-Since"];
        DateTime modifiedSince;
        if (string.IsNullOrEmpty(modifiedSinceHeader)
          || modifiedSinceHeader.Length == 0
          || !DateTime.TryParse(modifiedSinceHeader, out modifiedSince))
            return null;

        return modifiedSince;
    }
}
Related