三、通过jQuery的Ajax设置解决问题
实际上jQuery具有针对这个的Ajax设置,我们只需要按照如下的方式调用$.ajaxSetup方法禁止掉Ajaz的缓存机制。
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
$(function () {
$.ajaxSetup({ cache false });
window.setInterval(function () {
$.ajax({
url'@Url.Action("GetCurrentTime")',
success function (result) {
$("ul").append("<li>" + result + "</li>");
}
});
}, );
});
</script>
</head>
</html>
实际上jQuery的这个机制也是通过为请求地址添加不同的查询字符串后缀来实现的,这可以通过Fiddler拦截的请求来证实。

四、通过定制响应解决问题
我们可以通过请求的响应来控制浏览器针对结果的缓存,为此我们定义了如下一个名为NoCacheAttribute的ActionFilter。在实现的OnActionExecuted方法中,我们调用当前HttpResponse的SetCacheability方法将缓存选项设置为NoCache。该NoCacheAttribute特性被应用到GetCurrentTime方法后,运行我们的程序在IE中依然可以得到实时的时间。
public class HomeController Controller
{
public ActionResult Index()
{
return View();
}
[NoCache]
public string GetCurrentTime()
{
return DateTime.Now.ToLongTimeString();
}
}
public class NoCacheAttribute FilterAttribute, IActionFilter
{
public void OnActionExecuted(ActionExecutedContext filterContext)
{
filterContext.HttpContext.Response.Cache.SetCacheability(HttpCacheability.NoCache);
}
public void OnActionExecuting(ActionExecutingContext filterContext)
{}
}
实际NoCacheAttribute特性最终控制消息消息的Cache-Control报头,并将其设置为“no-cache”,指示浏览器不要对结果进行缓存。如下所示的是针对GetCurrentTime请求的响应消息:
HTTP/. OK Server ASP.NET Development Server/... Date Thu, Jan GMT X-AspNet-Version .. X-AspNetMvc-Version . Cache-Control no-cache Pragma no-cache Expires - Content-Type text/html; charset=utf- Content-Length Connection Close PM









