Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use System.Web.Caching in asp.net?

I have a class that looks like this:

using System.Collections.Generic;
using System.Web.Caching;

public static class MyCache
{
    private static string cacheKey = "mykey";

    public static Dictionary<string, bool> GetCacheValue(bool bypassCache)
    {
        var settings = Cache[cacheKey] as Dictionary<string, bool>; // error on this line

        // ...etc...

        return settings
    }
}

the problem I'm having is that this wont compile. The compiler says Cache can't be used the way I'm doing it. Here's the message:

'System.Web.Caching.Cache' is a 'type' but is used like a 'variable'

This perplexes me. I've googled the ASP.NET Cache API and have found many examples of Cache being used this way. Here's one of those examples:

// http://www.4guysfromrolla.com/articles/100902-1.aspx
value = Cache("key")

      - or -

value = Cache.Get("key")

When I try using Cache.Get() I get another error saying that it's not a static method.

Evidently I need to initialize an instance of Cache. Is this the correct way to use this API? A follow-up question is, does cached information persist across instances?

Thanks for your help.

like image 471
quakkels Avatar asked Sep 27 '13 15:09

quakkels


1 Answers

System.Web.Caching.Cache is a class - you see people using a property named Cache that is an instance of System.Web.Caching.Cache. If you're using it outside of a class that provides you with the Cache property, access it using System.Web.HttpRuntime.Cache:

var settings = System.Web.HttpRuntime.Cache[cacheKey] as Dictionary<string, bool>;
like image 184
zimdanen Avatar answered Sep 28 '22 00:09

zimdanen