Jon's Blog

.NET Development & More

Implementing Server Side Output Caching in an HTTP Handler

As you probably know, you can implement caching in an ASPX page using the OutputCache directive.  However, you can't use this in an ASHX handler.  So what if you are using a handler to server binary files from the database and you want to improve peformance by using server side output caching?  You'll just need to add some of your own caching logic in your code-behind.  Here is some sample code of how you can do this.  In this very basic example we are passing the ID of our object on the query string.

// Get ID from query string
int myID = Convert.ToInt32(context.Request.QueryString["ID"]);

// Attempt to get item from cache if it exists
string myCacheKey = "MyKey" + myID; // Unique Identifier
MyObject myObject = context.Cache[myCacheKey] as MyObject;

if (myObject == null)
// Item isn't cached; Grab business object from the database
myObject = MyObject.GetMyObject(myID);

// Add object to Cache using the cache key
// In this example we are caching for 30 minutes
context.Cache.Insert(myCacheKey, myObject,
null, DateTime.UtcNow.AddMinutes(30),

// Code to generate file from binary data here

Problem Debugging ASHX HTTP Handler

Today I had a problem hitting a breakpoint in an .ASHX file I created.  I noticed the project was using the built-in Visual Studio Development Server.  Once I switched over to using IIS I had no problem hitting the breakpoint.  I thought it was very strange, but hopefully this might help someone else out if they manage to find this post via Google.