Reputation: 43
I have read source code of one web application and seen that it used Cache object( Web.Caching.Cache) for caching data. In code behind files( aspx.cs files), it uses Page.Cache to get Cache while in others class-define files it uses HttpContext.Current.Cache to get Cache. I wonder why it not use the same option to get Cache. Can someone explain differences between Page.Cache and HttpContext.Current.Cache? Why use each one for each context above. Can I use Page.Cache or HttpContext.Current.Cache for both contexts above? Thanks in advance.
Upvotes: 3
Views: 595
Reputation: 460238
There is no difference, the former uses the current page instance and it's Cache
property, the latter uses the static
approach via HttpContext.Current.Cache
which would work also in a static method without page instance.
Both are referring to the same application cache.
So you can get the Cache
via Page
, for example in Page_Load
:
protected void Page_load(Object sender, EventArgs e)
{
System.Web.Caching.Cache cache = this.Cache;
}
or in a static method (which is used in a HttpContext
) via HttpContext.Current
:
static void Foo()
{
var context = HttpContext.Current;
if (context != null)
{
System.Web.Caching.Cache cache = context.Cache;
}
}
Upvotes: 3