Yas*_*ser 46 c# http-caching asp.net-web-api
我正在使用带有WEB API的ASP.NET MVC 4
我有以下操作,在下面显示的操作中,我的服务方法对方法进行db调用DoMagic()
并返回一个整数值,然后我在每个页面上使用该函数,使用ajax调用调用此操作.
以下是我的WEB API操作:
[OutputCache(Duration = 86400, VaryByParam = "none")]
[ActionName("GetMyMagicNumber")]
public int GetMyMagicNumber()
{
if (WebSecurity.IsAuthenticated)
{
var revenue = _magicService.DoMagic();
return revenue;
}
return 0;
}
Run Code Online (Sandbox Code Playgroud)
我的问题:我已经尝试过使用[OutputCache(Duration = 86400, VaryByParam = "none")]
,我除外,只有第一次进行数据库调用,然后对此操作的下一个后续请求将返回缓存值,但这不会发生.
再次进行db调用,db调用需要时间如何才能使这个工作?
Oak*_*nja 47
不幸的是,ASP.NET Web API中没有内置缓存.
看看这个让你走上正轨:http://www.strathweb.com/2012/05/output-caching-in-asp-net-web-api/
这里有更新的资源:https://github.com/filipw/AspNetWebApi-OutputCache
Sag*_*agi 20
在项目中添加对System.Runtime.Caching的引用.添加辅助类:
using System;
using System.Runtime.Caching;
public static class MemoryCacher
{
public static object GetValue(string key)
{
MemoryCache memoryCache = MemoryCache.Default;
return memoryCache.Get(key);
}
public static bool Add(string key, object value, DateTimeOffset absExpiration)
{
MemoryCache memoryCache = MemoryCache.Default;
return memoryCache.Add(key, value, absExpiration);
}
public static void Delete(string key)
{
MemoryCache memoryCache = MemoryCache.Default;
if (memoryCache.Contains(key))
{
memoryCache.Remove(key);
}
}
}
Run Code Online (Sandbox Code Playgroud)
然后从您的代码中获取或设置缓存中的对象:
list = (List <ChapterEx>)MemoryCacher.GetValue("CacheItem1");
Run Code Online (Sandbox Code Playgroud)
和
MemoryCacher.Add("CacheItem1", list, DateTimeOffset.UtcNow.AddYears(1));
Run Code Online (Sandbox Code Playgroud)
Cod*_*bie 15
正如OakNinja已经提到的,[OutputCache]
ASP.NET Web API目前不支持通过属性的输出缓存.
但是,有一些开源实现填补了这个空白:
一个小型库,将类似于MVC的"OutputCacheAttribute"的缓存选项带到Web API操作.
Github:https://github.com/filipw/Strathweb.CacheOutput
许可证:Apache v2
客户端和服务器端的ASP.NET Web API中的HTTP缓存实现.
Github:https://github.com/aliostad/CacheCow
许可证:麻省理工学院
注意:根据README项目,库不支持属性路由:
目前,CacheCow的属性设置不适用于属性路由.我个人认为你不应该使用属性路由...(来源:https://github.com/aliostad/CacheCow/blob/master/README.md)
Scott Hanselmann有一篇很好的博客文章,涵盖了两个功能集.
[ResponseCache]
现在在ASP.NET Core中受支持
功能可能看起来与客户端相同,[OutputCache]
但[ResponseCache]
仅适用于客户端。
响应缓存将与缓存相关的标头添加到响应中。这些标头指定您希望客户端,代理和中间件如何缓存响应。
https://docs.microsoft.com/zh-cn/aspnet/core/performance/caching/response
[ResponseCache(Duration = 3600)]
[HttpGet]
public IEnumerable<Product> Get()
{
return _service.GetAll();
}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
76722 次 |
最近记录: |