我有一个用 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 的“网络”选项卡中查看的响应:
根据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(来自缓存)
:
刷新后给我一个 304 Not Modified
:
问题解决了!希望这对其他人有帮助。
关于c# - 如何缓存 .NET Web API 请求(并使用 w/AngularJS $http),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17287144/