You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

ASP.NET MVC3如何仅禁用页面缓存而保留静态内容缓存?

解决方案:仅禁用ASP.NET业务页面缓存,保留静态资源缓存

完全可以实现这个需求,不用全局禁用所有缓存,下面是几种实用的方案:

1. 自定义Action过滤器(MVC推荐方案)

创建专属的缓存禁用过滤器,只给包含敏感业务数据的Action或Controller打上标记,精准控制缓存策略。

步骤:

  • 新建一个NoCacheAttribute类,继承ActionFilterAttribute:
public class NoCacheAttribute : ActionFilterAttribute
{
    public override void OnResultExecuting(ResultExecutingContext filterContext)
    {
        var response = filterContext.HttpContext.Response;
        
        // 设置禁用缓存的HTTP头
        response.Cache.SetCacheability(HttpCacheability.NoCache);
        response.Cache.SetNoStore();
        response.Cache.SetExpires(DateTime.UtcNow.AddDays(-1));
        response.Cache.AppendCacheExtension("must-revalidate, private");
        response.Headers.Add("Pragma", "no-cache");
        
        base.OnResultExecuting(filterContext);
    }
}
  • 在需要禁用缓存的Controller或Action上添加标记:
// 给整个Controller禁用缓存
[NoCache]
public class SensitiveDataController : Controller
{
    // 或者单独给某个Action禁用
    [NoCache]
    public ActionResult UserInfo()
    {
        return View();
    }
}

这里设置的HTTP头和全局配置一致:

  • Cache-Control: no-cache, no-store, must-revalidate, private
  • Pragma: no-cache
  • Expires: -1

2. 基类Controller统一处理

如果大部分业务Controller都需要禁用缓存,可以创建一个基类Controller,所有业务Controller继承它,统一设置缓存头:

public class BaseBusinessController : Controller
{
    protected override void OnResultExecuting(ResultExecutingContext filterContext)
    {
        var response = filterContext.HttpContext.Response;
        
        response.Cache.SetCacheability(HttpCacheability.NoCache);
        response.Cache.SetNoStore();
        response.Cache.SetExpires(DateTime.UtcNow.AddDays(-1));
        response.Cache.AppendCacheExtension("must-revalidate, private");
        response.Headers.Add("Pragma", "no-cache");
        
        base.OnResultExecuting(filterContext);
    }
}

// 业务Controller继承基类
public class OrderController : BaseBusinessController
{
    // 这里的Action自动应用禁用缓存策略
    public ActionResult OrderDetail(int id)
    {
        return View();
    }
}

3. 确保静态资源正常缓存

先移除web.config里的全局customHeaders配置,然后单独给静态资源设置缓存策略:
在web.config的<system.webServer>节点下添加:

<staticContent>
    <clientCache cacheControlMode="UseMaxAge" cacheControlMaxAge="7.00:00:00" />
</staticContent>

这个配置会让JS、CSS、图片等静态资源缓存7天,你可以根据需求调整cacheControlMaxAge的时长。

原理说明

静态资源(JS/CSS/图片等)默认不会经过ASP.NET MVC的Action管道,所以上面的Action过滤器只会作用于MVC的页面/接口,不会影响静态资源的缓存策略,完美实现“业务页面禁用缓存,静态资源正常缓存”的需求。

内容的提问来源于stack exchange,提问作者user13063200

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.28 21:13:23