Jav*_*per 186 .net c# asp.net-mvc jquery asp.net-mvc-3
我有一个ASP.NET MVC 3应用程序.此应用程序通过JQuery请求记录.JQuery回调一个以JSON格式返回结果的控制器动作.我无法证明这一点,但我担心我的数据可能会被缓存.
我只希望将缓存应用于特定操作,而不是所有操作.
是否有一个属性可以放在一个动作上以确保数据不会被缓存?如果没有,我如何确保浏览器每次都获得一组新记录而不是缓存集?
mat*_*mmo 298
要确保JQuery不缓存结果,请在ajax方法上添加以下内容:
$.ajax({
cache: false
//rest of your ajax setup
});
Run Code Online (Sandbox Code Playgroud)
或者为了防止MVC中的缓存,我们创建了自己的属性,你也可以这样做.这是我们的代码:
[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);
}
}
Run Code Online (Sandbox Code Playgroud)
然后用你的控制器装饰[NoCache]
.或者为所有你可以把属性放在你继承你的控制器的基类的类(如果你有的话),就像我们在这里:
[NoCache]
public class ControllerBase : Controller, IControllerBase
Run Code Online (Sandbox Code Playgroud)
如果您需要将这些属性设置为不可缓存,而不是装饰整个控制器,您还可以使用此属性修饰某些操作.
如果您的类或操作NoCache
在浏览器中呈现时没有,并且您想检查它是否正常工作,请记住在编译更改后,您需要在浏览器中执行"硬刷新"(Ctrl + F5).在您执行此操作之前,您的浏览器将保留旧的缓存版本,并且不会使用"正常刷新"(F5)刷新它.
Jag*_*uir 248
您可以使用内置缓存属性来防止缓存.
对于.net框架: [OutputCache(NoStore = true, Duration = 0)]
对于.net核心: [ResponseCache(NoStore = true, Duration = 0)]
请注意,无法强制浏览器禁用缓存.您可以做的最好的事情是提供大多数浏览器都会尊重的建议,通常采用标题或元标记的形式.此装饰器属性将禁用服务器缓存并添加此标头:Cache-Control: public, no-store, max-age=0
.它不会添加元标记.如果需要,可以在视图中手动添加.
此外,JQuery和其他客户端框架将尝试通过向URL添加内容(例如时间戳或GUID)来欺骗浏览器不使用其缓存的资源版本.这有效地使浏览器再次请求资源,但并不真正阻止缓存.
最后说明.您应该知道,资源也可以缓存在服务器和客户端之间.ISP,代理和其他网络设备也会缓存资源,它们通常使用内部规则而不查看实际资源.关于这些,你无能为力.好消息是它们通常缓存较短的时间范围,如秒或分钟.
Chr*_*ini 47
所有你需要的是:
[OutputCache(Duration=0)]
public JsonResult MyAction(
Run Code Online (Sandbox Code Playgroud)
或者,如果要为整个Controller禁用它:
[OutputCache(Duration=0)]
public class MyController
Run Code Online (Sandbox Code Playgroud)
尽管这里的评论存在争议,但这足以禁用浏览器缓存 - 这会导致ASP.Net发出响应标头,告诉浏览器文档立即过期:
dfo*_*tun 13
在控制器操作中,向标题添加以下行
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.
Run Code Online (Sandbox Code Playgroud)
这是NoCache
mattytommo提出的属性,使用来自Chris Moschini的答案的信息进行了简化:
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method)]
public sealed class NoCacheAttribute : OutputCacheAttribute
{
public NoCacheAttribute()
{
this.Duration = 0;
}
}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
157760 次 |
最近记录: |