1.问题描述:
IE 浏览器(版本是 IE 11)在发起 GET 请求,浏览器会直接使用缓存数据,不会请求后台,对于实时性需求不适用。在使用 其他浏览器时未发现浏览器并未发现 GET 请求的缓存问题。
2.问题解决
2.1 方案一
最简单的方法在我们的 get 请求后面添加一个参数 t = 时间戳
t = new Date().getTime();
例如:
http://127.0.0.1/api/user/list?pageNo=1&pageSize=10&t=1516693948975
2.2 方案二
通过jquery的ajax设置来解决
实际上jQuery具有针对这个的Ajax设置,我们只需要按照如下的方式调用$.ajaxSetup方法禁止掉Ajaz的缓存机制。
<!DOCTYPE html>
2: <html>
3: <head>
4: <script type="text/javascript">
5: $(function () {
6: $.ajaxSetup({ cache: false });
7: window.setInterval(function () {
8: $.ajax({
9: url:'@Url.Action("GetCurrentTime")',
10: success: function (result) {
11: $("ul").append("<li>" + result + "</li>");
12: }
13: });
14: }, 5000);
15: });
16: </script>
17: </head>
18: </html>
2.3 方案三(笔者没试过)
我们可以通过请求的响应来控制浏览器针对结果的缓存,为此我们定义了如下一个名为NoCacheAttribute的ActionFilter。在实现的OnActionExecuted方法中,我们调用当前HttpResponse的SetCacheability方法将缓存选项设置为NoCache。该NoCacheAttribute特性被应用到GetCurrentTime方法后,运行我们的程序在IE中依然可以得到实时的时间。
1: public class HomeController : Controller
2: {
3: public ActionResult Index()
4: {
5: return View();
6: }
7:
8: [NoCache]
9: public string GetCurrentTime()
10: {
11: return DateTime.Now.ToLongTimeString();
12: }
13: }
14: public class NoCacheAttribute : FilterAttribute, IActionFilter
15: {
16: public void OnActionExecuted(ActionExecutedContext filterContext)
17: {
18: filterContext.HttpContext.Response.Cache.SetCacheability(HttpCacheability.NoCache);
19: }
20:
21: public void OnActionExecuting(ActionExecutingContext filterContext)
22: {}
23: }
实际NoCacheAttribute特性最终控制消息消息的Cache-Control报头,并将其设置为“no-cache”,指示浏览器不要对结果进行缓存。如下所示的是针对GetCurrentTime请求的响应消息:
1: HTTP/1.1 200 OK
2: Server: ASP.NET Development Server/10.0.0.0
3: Date: Thu, 03 Jan 2013 12:54:56 GMT
4: X-AspNet-Version: 4.0.30319
5: X-AspNetMvc-Version: 4.0
6: Cache-Control: no-cache
7: Pragma: no-cache
8: Expires: -1
9: Content-Type: text/html; charset=utf-8
10: Content-Length: 10
11: Connection: Close
12:
13: 8:54:56 PM