Question on Caching an HttpHandler for Speed

Ok, I need some help with something. I'm building a HttpHandler that uses an XmlTextWriter to output some custom-generated XML to a requester. I'd like to be able to cache the generated document, because chances are good that the data won't change for a while, and I don't want to hit the DB every time. The problem is, with the following code, I don't think I can do it:

1Dim w As XmlTextWriter = New XmlTextWriter(context.Response.Output)
2w.Formatting = Formatting.Indented
3w.WriteStartDocument()
4w.WriteEndDocument()

So, what would be a better way to generate the document, store it in the cache, and output it from the cache? I'm just not familiar enough with XML in .NET to know. Thanks in advance.

 

7 Comments

  • Write the XML to a string first (via StringWriter, for example), and cache that. Then just stream the string back out to Response.Output.



    Jim

  • Or better write to a byte array (via MemoryStream) instead of string to avoid encoding issues.

  • here's the general idea that i would use



    if(cacheExpired)

    {

    //generate xml that outputs to the cache file

    //not to the response

    }



    // stream the text from the cache file to

    // the response

  • You could use output caching via Response.Cache(HttpCachePolicy) and send an ETag. That will minimize the number of actual hits to the handler

  • What you can do is use an ASMX instead of an HttpHandler, and set a value to the CacheDuration parameter of the WebMethod attribute.



    This is what I do for RSS for example:

    The URL is .../Tools.asmx/GetLatestAdditions_Rss

    The method in the ASMX:

    [WebMethod(CacheDuration=120)]

    XmlDocument GetLatestAdditions_Rss()

    {

    ...

    }

  • The simplest approach is to just use the Response.Cache property to control the caching policy of the output. You can do this right before the above code.



    This will give you all the semantics (and more) of the <%@ OutputCache %> directive in a .aspx page. The beauty of it, though, is that you can set everything programmatically -- so you have even more control with this approach.



    Hope this helps,



    Scott

  • What if the resource isn't going to be pulled from a browser though? For example, what if you use a WebMethod to get the data?

Comments have been disabled for this content.