prevent缓存在ASP.NET MVC的具体行动,使用属性缓存、属性、具体、行动

2023-09-02 20:41:44 作者:甜心大萝卜

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

I have an ASP.NET MVC 3 application. This application requests records through JQuery. JQuery calls back to a controller action that returns results in JSON format. I have not been able to prove this, but I'm concerned that my data may be getting cached.

我只想缓存被应用到具体的行动,而不是对所有的操作。

I only want the caching to be applied to specific actions, not for all actions.

有没有办法,我可以把一个行动,以确保数据不会缓存的属性?如果没有,我怎么确保浏览器获得,而不是一个缓存设置一组新的记录每一次,?

Is there an attribute that I can put on an action to ensure that the data does not get cached? If not, how do I ensure that the browser gets a new set of records each time, instead of a cached set?

推荐答案

要确保jQuery是不缓存的结果,你的AJAX方法,把下面的:

To ensure that JQuery isn't caching the results, on your ajax methods, put the following:

$.ajax({
    cache: false
    //rest of your ajax setup
});

或者在MVC prevent缓存,我们创建了自己的属性,你可以做同样的。这是我们的code:

Or to prevent caching in MVC, we created our own attribute, you could do the same. Here's our code:

[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method)]
public sealed class NoCacheAttribute : ActionFilterAttribute
{
    public override void OnResultExecuting(ResultExecutingContext filterContext)
    {
        filterContext.HttpContext.Response.Cache.SetExpires(DateTime.UtcNow.AddDays(-1));
        filterContext.HttpContext.Response.Cache.SetValidUntilExpires(false);
        filterContext.HttpContext.Response.Cache.SetRevalidation(HttpCacheRevalidation.AllCaches);
        filterContext.HttpContext.Response.Cache.SetCacheability(HttpCacheability.NoCache);
        filterContext.HttpContext.Response.Cache.SetNoStore();

        base.OnResultExecuting(filterContext);
    }
}

然后,只需装饰与控制器[NOCACHE] 。或者做所有你可以只是把属性的类,你继承你的控制器(如果有的话),就像我们这里的基类的:

Then just decorate your controller with [NoCache]. OR to do it for all you could just put the attribute on the class of the base class that you inherit your controllers from (if you have one) like we have here:

[NoCache]
public class ControllerBase : Controller, IControllerBase

您还可以装饰一些行动具有这种属性,如果你需要它们是不可缓存的,而不是装饰的整体控制。

You can also decorate some of the actions with this attribute if you need them to be non-cacheable, instead of decorating the whole controller.

如果你的类或动作没有非缓存,当它被呈现在您的浏览器,并要检查它的工作,请记住,编译您需要更改后在浏览器中做一个硬刷新(按Ctrl + F5)。直到你这样做,你的浏览器将保持旧的高速缓存版本,而不会与正常刷新(F5)刷新。

If your class or action didn't have NoCache when it was rendered in your browser and you want to check it's working, remember that after compiling the changes you need to do a "hard refresh" (Ctrl+F5) in your browser. Until you do so, your browser will keep the old cached version, and won't refresh it with a "normal refresh" (F5).