我有一个ASP。NET MVC 3应用程序。这个应用程序通过jQuery请求记录。jQuery回调控制器动作,返回JSON格式的结果。我还不能证明这一点,但我担心我的数据可能会被缓存。

我只希望缓存应用于特定的操作,而不是所有的操作。

是否有一个属性可以放在操作上以确保数据不会被缓存?如果不是,我如何确保浏览器每次都获得一组新的记录,而不是缓存的记录集?


当前回答

你只需要:

[OutputCache(Duration=0)]
public JsonResult MyAction(

或者,如果你想为整个控制器禁用它:

[OutputCache(Duration=0)]
public class MyController

尽管在这里的评论中有争论,但这足以禁用浏览器缓存——这会导致ASP。Net发出响应头,告诉浏览器文档立即过期:

其他回答

你只需要:

[OutputCache(Duration=0)]
public JsonResult MyAction(

或者,如果你想为整个控制器禁用它:

[OutputCache(Duration=0)]
public class MyController

尽管在这里的评论中有争论,但这足以禁用浏览器缓存——这会导致ASP。Net发出响应头,告诉浏览器文档立即过期:

MVC中的输出缓存

[OutputCache(NoStore = true, Duration = 0, Location="None", VaryByParam = "*")]

OR
[OutputCache(NoStore = true, Duration = 0, VaryByParam = "None")]

下面是mattytommo提出的NoCache属性,通过使用Chris Moschini的答案来简化:

[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method)]
public sealed class NoCacheAttribute : OutputCacheAttribute
{
    public NoCacheAttribute()
    {
        this.Duration = 0;
    }
}

在控制器动作中,将以下行附加到标题

    public ActionResult Create(string PositionID)
    {
        Response.AppendHeader("Cache-Control", "no-cache, no-store, must-revalidate"); // HTTP 1.1.
        Response.AppendHeader("Pragma", "no-cache"); // HTTP 1.0.
        Response.AppendHeader("Expires", "0"); // Proxies.

对于MVC6 (DNX),没有System.Web.OutputCacheAttribute

注意:设置NoStore Duration参数时不考虑。可以为第一次注册设置初始持续时间,并使用自定义属性覆盖该持续时间。

但是我们有microsoft。aspnet。mvc。filters。responsecachefilter

 public void ConfigureServices(IServiceCollection services)
        ...
        services.AddMvc(config=>
        {
            config.Filters.Add(
                 new ResponseCacheFilter(
                    new CacheProfile() { 
                      NoStore=true
                     }));
        }
        ...
       )

可以使用自定义属性覆盖初始过滤器

    [AttributeUsage(AttributeTargets.Class | AttributeTargets.Method)]
    public sealed class NoCacheAttribute : ActionFilterAttribute
    {
        public override void OnResultExecuting(ResultExecutingContext filterContext)
        {
            var filter=filterContext.Filters.Where(t => t.GetType() == typeof(ResponseCacheFilter)).FirstOrDefault();
            if (filter != null)
            {
                ResponseCacheFilter f = (ResponseCacheFilter)filter;
                f.NoStore = true;
                //f.Duration = 0;
            }

            base.OnResultExecuting(filterContext);
        }
    }

这是一个用例

    [NoCache]
    [HttpGet]
    public JsonResult Get()
    {            
        return Json(new DateTime());
    }