Ajax.NET and System.Web.Caching.Cache

Today I found an article about caching using Ajax.NET. In the article the author said that the Cache object is not working with Ajax.NET. I have done a small example to show how to use the Cache object in AJAX methods.

The ZIP file is a ASP.NET 2.0 project, but the default.aspx (inline code) will work with .NET 1.x, too.

Update: Instead of System.Web.HttpContext.Current.Cache/Session/Application you can also use Context.Cache/Session/Application if you are using System.Web.UI.Page as you Ajax.NET method class.

5 Comments

  • Joe said

    What's the article your referring to? I'd be surprised to see anyone assert that the ASP.NET (server-side) Cache object is not working with Ajax.NET: it's available to any ASP.NET app as your sample demonstrates (in fact to any .NET app - it's not restricted to ASP.NET).

    I have however seen articles discussing issues with the browser (client-side) cache, which is a different matter altogether.

  • Michael Schwarz said

    @Joe: I cannot find the article because I deleted my temporary internet files and... A lot of developers don't know the HttpContext.Current object, and from external classes (not System.UI.Page) you have to use this. If you have a look in the code of System.Web.UI.Page.Context: there is a fallback to System.Web.HttpContext.Current if the internal variable is not set.

  • Joe said

    Michael, you're absolutely right that a lot of developers are unaware that you can use HttpContext.Current from external classes.
    Actually in the case of the Cache I like to go further in external classes: HttpContext.Current will be null if the class is called outside the context of an Http request (e.g. in a worker thread in an ASP.NET app, or in a non-ASP.NET app). In this case you can use System.Web.HttpRuntime.Cache to access the cache for the current application domain, which works anywhere.

  • AzamSharp said

    Hi Michael,

    I used your approach to get the caching work and it worked!

    HttpContext.Current.Cache["MyData"] = "SomeData";
    return (string) HttpContext.Current.Cache["MyData"];

    interestely if I use the Page cache object than it wont work:

    Cache["MyData"] = "SomeData";
    return (string) Cache["MyData"];

Comments have been disabled for this content.