How to make caching dependent on a boolean value in web.config file? [duplicate]
开发者_开发知识库Possible Duplicate:
Asp.NET Caching
I'd like to be able to switch caching on or off depending on a value set in web.config file. Say for instance if the value is 'true' then caching is enabled. Thank you
You need to add a key in your web.config. like,
<add key="AllowCaching" value="true"/>
then where ever you want to do caching you may do:
DataSet dataSet;
if(bool.Parse(System.Configuration.ConfigurationManager.AppSettings["AllowCaching"]))
{
//do caching
if (Context.Cache["YourDataKey"] == null)
{
dataSet = GetDataForDataset();
object objDataset = (object)dataSet;
Context.Cache.Insert("YourDataKey", objDataset, null, DateTime.Now.AddSeconds(30),
System.Web.Caching.Cache.NoSlidingExpiration);
}
else
{
dataSet = (DataSet)Context.Cache["YourDataKey"];
}
}
else
{
//dont do caching
dataSet = GetDataForDataset();
}
where 30 is the number of seconds for which you want to hold data in cache.
精彩评论