ASP.Net Web API 输出缓存(转)
出处:http://www.cnblogs.com/ajilisiwei/p/6112078.html
原文的转载地址:http://www.strathweb.com/2012/05/output-caching-in-asp-net-web-api/
一.Nuget安装相关dll
Web API 2 : Install-Package Strathweb.CacheOutput.WebApi2
Web API 1 : Install-Package Strathweb.CacheOutput
二.新建一个 ActionFilterAttribute ,并重写相关方法
public class WebApiOutputCacheAttribute : ActionFilterAttribute
{
// 缓存时间 /秒
private int _timespan;
// 客户端缓存时间 /秒
private int _clientTimeSpan;
// 是否为匿名用户缓存
private bool _anonymousOnly;
// 缓存索引键
private string _cachekey;
// 缓存仓库
private static readonly ObjectCache WebApiCache = MemoryCache.Default;
public WebApiOutputCacheAttribute(int timespan, int clientTimeSpan, bool anonymousOnly)
{
_timespan = timespan;
_clientTimeSpan = clientTimeSpan;
_anonymousOnly = anonymousOnly;
}
//是否缓存
private bool _isCacheable(HttpActionContext ac)
{
if (_timespan > 0 && _clientTimeSpan > 0)
{
if (_anonymousOnly)
if (Thread.CurrentPrincipal.Identity.IsAuthenticated)
return false;
if (ac.Request.Method == HttpMethod.Get) return true;
}
else
{
throw new InvalidOperationException("Wrong Arguments");
}
return false;
}
private CacheControlHeaderValue setClientCache()
{
var cachecontrol = new CacheControlHeaderValue();
cachecontrol.MaxAge = TimeSpan.FromSeconds(_clientTimeSpan);
cachecontrol.MustRevalidate = true;
return cachecontrol;
}
//Action调用前执行的方法
public override void OnActionExecuting(HttpActionContext ac)
{
if (ac != null)
{
if (_isCacheable(ac))
{
_cachekey = string.Join(":", new string[] { ac.Request.RequestUri.AbsolutePath, ac.Request.Headers.Accept.FirstOrDefault().ToString() });
if (WebApiCache.Contains(_cachekey))
{
var val = (string)WebApiCache.Get(_cachekey);
if (val != null)
{
ac.Response = ac.Request.CreateResponse();
ac.Response.Content = new StringContent(val);
var contenttype = (MediaTypeHeaderValue)WebApiCache.Get(_cachekey + ":response-ct");
if (contenttype == null)
contenttype = new MediaTypeHeaderValue(_cachekey.Split(':')[1]);
ac.Response.Content.Headers.ContentType = contenttype;
ac.Response.Headers.CacheControl = setClientCache();
return;
}
}
}
}
else
{
throw new ArgumentNullException("actionContext");
}
}
//Action调用后执行方法
public override void OnActionExecuted(HttpActionExecutedContext actionExecutedContext)
{
if (!(WebApiCache.Contains(_cachekey)))
{
var body = actionExecutedContext.Response.Content.ReadAsStringAsync().Result;
WebApiCache.Add(_cachekey, body, DateTime.Now.AddSeconds(_timespan));
WebApiCache.Add(_cachekey + ":response-ct", actionExecutedContext.Response.Content.Headers.ContentType, DateTime.Now.AddSeconds(_timespan));
}
if (_isCacheable(actionExecutedContext.ActionContext))
actionExecutedContext.ActionContext.Response.Headers.CacheControl = setClientCache();
}
}
三. 控制器的需要添加缓存的Get方法添加该过滤器
[WebApiOutputCache(120,60,false)]
public string GetShoppingCart()
{
return "Hello World";
}
启动,观察打断点,观察效果。整个过程是:启动时先初始化该缓存过滤器,客户端调用添加了该过滤器的Get方法后,进入OnActionExecuting方法,判断是否有相关的缓存存在,如果有则直接返回结果,如否,则调用控制器的Action,再调用OnActionExecuted方法添加相关的缓存键值对并设置缓存过期时间,返回结果。
最新文章
- Spring MVC注解开发入门
- 基于HTML5 Canvas实现的图片马赛克模糊特效
- javascript 奇淫巧技44招
- Linq集合
- 对于spark以及hadoop的几个疑问(转)
- EL表达式与JSTL
- ACCESS作为网站数据库的弊端
- BZOJ-1207 打鼹鼠 DP(LIS)
- Apple Remote Push Notifications
- PHP字符串操作常用函数
- eclipse设置web项目发布到tomcat根目录下
- SSH深度历险(三) EJB Session Bean有状态和无状态的差别与联系
- Web设计新手应知道的10个锦囊妙计
- windows 下搭建 git 服务器 gogs
- Btrace官方教程-中文版
- java开发常用的日期格式转换工具类
- 分布式中的 transaction log
- TensorFlow框架下的RNN实践小结
- C语言入门:04.数据类型、常量、变量
- Oracle SQL之 序列使用限制
热门文章
- [转]基于Oracle的EntityFramework的WEBAPI2的实现(一)——准备工作
- 关于 android百度地图 调用 地理位置 经纬度坐标,只调用一次的解决方法,通知栏不总是 搜索 GPS 。。。
- 解决标准FPGA资源丰富却浪费的问题
- EF-CodeFirst系列100
- [题解] [NOIP2008] 双栈排序——关系的冲突至图论解法
- shred_linux_unix
- HDU 2846 Repository(字典树,每个子串建树,*s的使用)
- git grade 版本下载及安装
- Javascript继承机制的设计思想
- TensorFlow计算图,张量,会话基础知识