HttpContext.Current.Cache 和HttpRuntime.Cache的区别

本文详细解析了ASP.NET中HttpContext.Current.Cache与HttpRuntime.Cache的区别,通过源码对比及实例演示,阐述了两者在不同场景下的使用特点。

原文:http://blog.youkuaiyun.com/qwlovedzm/article/details/7024405

先看MSDN上的解释:
      HttpContext.Current.Cache:为当前 HTTP 请求获取Cache对象。
      HttpRuntime.Cache:获取当前应用程序的Cache。 
      我们再用.NET Reflector工具看看HttpContext.Cache和HttpRuntime.Cache的实现:

HttpContext.Cache和HttpRuntime.Cache实现
    //System.Web.HttpContext.Cache属性实现
    public sealed class HttpContext
    {
        public Cache Cache
        {
            get
            {
                return HttpRuntime.Cache;
            }
        }
    }


    //System.Web.HttpRuntime.Cache属性实现
    public sealed class HttpRuntime
    {
        public static Cache Cache
        {
            get
            {
                if (AspInstallDirectoryInternal == null)
                {
                    throw new HttpException(SR.GetString("Aspnet_not_installed", new object[] { VersionInfo.SystemWebVersion }));
                }
                Cache cache = _theRuntime._cachePublic;
                if (cache == null)
                {
                    CacheInternal cacheInternal = CacheInternal;
                    CacheSection cacheSection = RuntimeConfig.GetAppConfig().Cache;
                    cacheInternal.ReadCacheInternalConfig(cacheSection);
                    _theRuntime._cachePublic = cacheInternal.CachePublic;
                    cache = _theRuntime._cachePublic;
                }
                return cache;
            }
        }
    }

       通过上面的代码我们可以看出:HttpContext.Current.Cache是调用HttpRuntime.Cache实现的,两者指向同一Cache对象。那么两者到底有没有区别的?既然两个指向的是同一Cache对象,两者的差别只能出现在HttpContext和HttpRuntime上了。我们再来看看MSDN中HttpContext和HttpRuntime的定义。
      HttpContext:封装有关个别HTTP请求的所有HTTP特定的信息,HttpContext.Current为当前的HTTP请求获取HttpContext对象。
      HttpRuntime:为当前应用程序提供一组ASP.NET运行时服务。

      由上面的定义可以看出:HttpRuntime.Cache相当于就是一个缓存具体实现类,这个类虽然被放在了System.Web命名空间下,但是非Web应用下也是可以使用;HttpContext.Current.Cache是对上述缓存类的封装,由于封装到了HttpContext类中,局限于只能在知道HttpContext下使用,即只能用于Web应用。

      下面的例子可以很好的说明这一点:

HttpContext.Cache和HttpRuntime.Cache的示例
    class CacheTest
    {
        static void Main(string[] args)
        {       
            System.Web.Caching.Cache httpRuntimeCache = System.Web.HttpRuntime.Cache;
            httpRuntimeCache.Insert("httpRuntimeCache", "I am stored in HttpRuntime.Cache");

            if (httpRuntimeCache != null)
            {
                Console.WriteLine("httpRuntimeCache:" + httpRuntimeCache["httpRuntimeCache"]);
            }

            System.Web.HttpContext httpContext = System.Web.HttpContext.Current;
            if (httpContext == null)
            {
                Console.WriteLine("HttpContext object is null in Console Project");
            }
            else
            {
                System.Web.Caching.Cache httpContextCache = httpContext.Cache;
                httpContextCache.Insert("httpContextCache", "I am stored in HttpRuntime.Cache");
                if (httpContextCache == null)
                {
                    Console.WriteLine("httpContextCache is null");
                }
            }
             
            Console.ReadLine();
        }
    }

      输出结果:httpRuntimeCache:I am stored in HttpRuntime.Cache
      HttpContext object is null in Console Project

      综上:我们在使用Cache时,尽量使用HttpRuntime.Cache,既能减少出错,也减少了一次函数调用。

      参考资料:HttpRuntime.Cache 与HttpContext.Current.Cache的疑问,HttpRuntime.Cache vs. HttpContext.Current.Cache


在 ASP.NET 中,`HttpContext.Current.Session.Timeout` 表示会话(Session)的超时时间(单位:分钟),它定义了用户在不活动多长时间后,其 Session 数据将被服务器清除。 --- ### ✅ `Session.Timeout` 的最大值 #### **理论最大值:525600 分钟(即 1 年)** ASP.NET 的 `Session.Timeout` 是一个 `int` 类型的属性,表示分钟数。 虽然 .NET 层面没有硬编码限制为某个具体数值(如 59999),但**实际使用中受 IIS 系统行为限制**。 #### 🔍 实际推荐最大值:**1440 分钟(24 小时)** - 超过这个值可能导致: - IIS 应用程序池回收 - 服务器内存压力增大 - 安全风险增加(长期未注销的会话) > ⚠️ 注意:IIS 默认应用程序池每 29 小时自动回收一次,即使 Session 设置为 1 年,也会因 App Pool 回收而丢失 Session(除非使用 State Server 或 SQL Server 持久化)。 --- ### 🧩 设置 Session Timeout 示例 #### 1. 在 `web.config` 中设置: ```xml <configuration> <system.web> <sessionState mode="InProc" cookieless="false" timeout="1440" /> <!-- 最大建议值 --> </system.web> </configuration> ``` #### 2. 在代码中读取或动态修改(注意:只能读取,不能运行时修改): ```csharp // 读取当前 Session 超时时间 int timeoutMinutes = HttpContext.Current.Session.Timeout; Console.WriteLine($"Session Timeout: {timeoutMinutes} 分钟"); // ❌ 错误:以下代码不会生效! // HttpContext.Current.Session.Timeout = 20; // 编译错误或无效 ``` > ⚠️ **重要提示**:`Session.Timeout` 只能通过 `web.config` 设置,**不能在运行时更改**。 --- ### 📊 不同 Session Mode 的影响 | Mode | 是否支持长超时 | 说明 | |------|----------------|------| | `InProc`(默认) | ❌ 不推荐长超时 | 存在于内存中,AppDomain 重启即丢失 | | `StateServer` | ✅ 支持较长超时 | 独立进程,可跨 AppDomain | | `SQLServer` | ✅ 支持持久化超时 | 数据库存储,适合高可用场景 | | `Custom` | ✅ 取决于实现 | 如 Redis、MongoDB 等 | --- ### 💡 如何实现“永久会话”? 如果你希望用户“记住登录状态”,应使用 **Forms Authentication + 持久 Cookie** 或 **JWT Token**,而不是依赖 Session。 ```csharp // 示例:设置持久化 Forms 认证 Cookie FormsAuthentication.SetAuthCookie("username", createPersistentCookie: true); // 可配合 web.config 设置较长时间 ``` ```xml <authentication mode="Forms"> <forms timeout="1440" /> <!-- 单位:分钟 --> </authentication> ``` --- ### 🛑 常见误区 | 误区 | 正确理解 | |------|----------| | 可以设置 `timeout="99999"` 实现永不过期 | 实际受限于 App Pool 回收、内存、IIS 配置等 | | 运行时可以修改 `Session.Timeout` | 不可以,只读属性 | | Session 超时后用户仍能访问 | 需重新登录或重建 Session | --- ### ✅ 最佳实践建议 1. **生产环境建议设置为 20~60 分钟**(安全考虑) 2. 若需长时间保持状态,使用: - JWT Token - Refresh Token - 持久化 Cookie + 后端 Token 存储(如 Redis) 3. 使用 `SQLServer` 或 `Redis` 模式存储 Session 以支持长超时 4. 避免存储大量数据在 Session 中 ---
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值