随笔 - 435  文章 - 0  评论 - 111  阅读 - 62万 
I see several reference to using the ASP.NET 2.0 Cache object in C# where
the documentation just shows snippets like this:
if (Cache["sometoken"] == null)
... do something

However when I use this code in a C# class that is called from an ASP.NET
page, the compiler gives this error:
'Cache' is a tpe and cannot be used as an expression

Furthermore when I type in Cache and press the "." for intellisense, the
only things that pop up are Equals, NoAbsoluteExpiration,
NoSliderExpiration, ReferenceEquals. No methods like Add, Insert and so
forth show up.

This drove me crazy for a while. Then I decided to try my cache code
directly in my ASP.NET code behind page and it worked just fine.

Eventually after mucking around for a while I found that if I did this in my
C# class file then things worked correctly:

public Cache MyCache;
MyCache = System.Web.HttpContext.Current.Cache;

and now I can use if (MyCache["sometoken'] == null) from my C# class and it
works just fine.

A couple of questions:

1) Is this really necessary or am I referencing or doing something in
correctly?

2) Is there another approach to accessing the Cache from a C# class called
by a ASP.NET code behind, or did I stumble upon the right approach by what I
am using here?

Hopefully I'll get some clarification as to what is/was going on and why
this was necessary, and hopefully someone will find this post one day and it
will save them a lot of time.

Thanks,

Steve


------------------------------------------------------------------------------

Steve,

That's what you had to do. The Cache object is used by the .aspx page
natively and therefore the object has already been instantiated. In a class
file the Cache object is not already being used so you had to explicitly
create a holder for it and then get the cache object being used on the page.

Short story, you're doing it exactly right.

--
Sincerely,

S. Justin Gengo, MCP
Web Developer / Programmer


be sure System.Web.dll is references by project your class is in, and to get
the current Cache object being used by the asp.net, call
System.Web.HttpContect.Current.Cache
posted on   Gu  阅读(230)  评论(0编辑  收藏  举报
编辑推荐:
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
阅读排行:
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本
· C#/.NET/.NET Core优秀项目和框架2025年2月简报
· 什么是nginx的强缓存和协商缓存
· 一文读懂知识蒸馏
· Manus爆火,是硬核还是营销?
点击右上角即可分享
微信分享提示