c# - 如何缓存 .NET Web API 请求(并使用 w/AngularJS $http)

标签 c# caching angularjs asp.net-web-api

我有一个用 ASP.NET 编写的 Web API,我通过 AngularJS $http 使用它。

我已经在我的 AngularJS 工厂中启用了缓存,但每个请求仍然返回 200 的响应,而不是 200(来自缓存)304(对于每个请求,我的意思是在同一页面上多次发出相同的 Web API 请求,重新访问我已经访问过的包含 Web API 请求的页面,刷新所述页面等)。

angular.module('mapModule')
    .factory('GoogleMapService', ['$http', function ($http) {
         var googleMapService = {               
            getTags: function () {
                // $http returns a promise, which has a 'then' function, which also returns a promise
                return $http({ cache: true, dataType: 'json', url: '/api/map/GetTags', method: 'GET', data: '' })
                .then(function (response) {                     
                    return response.data;
                });
            };

        return googleMapService;
    }]);

我是否遗漏了 AngularJS 方面的内容?或者这是一个 Web API 问题。还是两者兼而有之?

最佳答案

原来这是一个 Web API 的东西。我忽略了响应 header 明确指出缓存已禁用这一事实。

在 Google Chrome 的“网络”选项卡中查看的响应:

enter image description here

根据further investigation (如上图所示),缓存在 Web API Controller 中被禁用。甚至不支持常规 MVC Controller 中使用的 [OutputCache] 属性。

幸运的是我找到了这个博客: http://www.strathweb.com/2012/05/output-caching-in-asp-net-web-api/

这让我想到了这两个解决方案:

我决定使用 CacheOutput,因为它允许我使用如下属性:

[CacheOutputUntilToday] 支持服务器和客户端缓存。

或者如果我想 just use client-side caching我可以使用类似的东西:

[CacheOutput(ClientTimeSpan = 100, ServerTimeSpan = 0)]

CacheCow 的方法乍一看似乎更容易一些。如果需要,以后更容易重构。

现在额外的请求给我 200(来自缓存):

enter image description here

刷新后给我一个 304 Not Modified:

enter image description here

问题解决了!希望这对其他人有帮助。

关于c# - 如何缓存 .NET Web API 请求(并使用 w/AngularJS $http),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17287144/

相关文章:

c# 将具有 ctrl+z 的字符串转换为常规字符串

c# - 将对象数组序列化为 JSON

c# - 缓存过期未按预期工作

java - Infinispan singleFileStore 缓存可重启性

javascript - 保留在 promise 内获得的值 - Angular

javascript - 什么是 Angular Material 中的 mdLiveAnnouncer 及其工作原理?

javascript - 如何在 ui-router 中使用单独的模板?

c# - 使逐字字符串文字自动缩进以与附近的代码保持一致

c# - 使用声明和表格

c# - 在 ASP.Net 中,在 system.web.caching 中存储 int 的最佳方式是什么?