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方法添加相关的缓存键值对并设置缓存过期时间,返回结果。
ASP.Net Web API 输出缓存(转)的更多相关文章
- ASP.Net Web API 输出缓存 转载 -- Output caching in ASP.NET Web API
一.Nuget安装相关dll Web API 2 : Install-Package Strathweb.CacheOutput.WebApi2 Web API 1 : Install-Package ...
- ASP.NET Web API实现缓存的2种方式
在ASP.NET Web API中实现缓存大致有2种思路.一种是通过ETag, 一种是通过类似ASP.NET MVC中的OutputCache. 通过ETag实现缓存 首先安装cachecow.ser ...
- 在asp.net web api中利用过滤器设置输出缓存
介绍 本文将介绍如何在asp.net web api中利用过滤器属性实现缓存. 实现过程 1,首先在web.config文件下appsettings下定义“CacheEnabled”和“CacheTi ...
- ASP.NET Web API中通过ETag实现缓存
通常情况下Server是无状态的,在ASP.NET Web API中,我们可以让服务端响应体中产生ETag属性,起到缓存的作用.大致实现原理是: 1.服务端的响应体中返回一个ETag属性2.客户端通过 ...
- ASP.NET Web API通过ActionFilter来实现缓存
using System; using System.Collections.Generic; using System.Linq; using System.Threading; using Sys ...
- 目标HttpController在ASP.NET Web API中是如何被激活的:目标HttpController的创建
目标HttpController在ASP.NET Web API中是如何被激活的:目标HttpController的创建 通过上面的介绍我们知道利用HttpControllerSelector可以根据 ...
- 目标HttpController在ASP.NET Web API中是如何被激活的:目标HttpController的选择
目标HttpController在ASP.NET Web API中是如何被激活的:目标HttpController的选择 ASP.NET Web API能够根据请求激活目标HttpController ...
- 在一个空ASP.NET Web项目上创建一个ASP.NET Web API 2.0应用
由于ASP.NET Web API具有与ASP.NET MVC类似的编程方式,再加上目前市面上专门介绍ASP.NET Web API 的书籍少之又少(我们看到的相关内容往往是某本介绍ASP.NET M ...
- ASP.NET Web API Model-ParameterBinding
ASP.NET Web API Model-ParameterBinding 前言 通过上个篇幅的学习了解Model绑定的基础知识,然而在ASP.NET Web API中Model绑定功能模块并不是被 ...
随机推荐
- POJ3259 Wormholes 【Bellmanford推断是否存在负回路】
版权声明:本文为博主原创文章,未经博主同意不得转载. https://blog.csdn.net/u011775691/article/details/27612757 非常easy的bellmanf ...
- load/domContentLoaded事件、异步/延迟Js 与DOM解析
一.DOMContentLoaded 与 load事件 关于load和DOMContentLoaded事件,mdn对于它们是这样描述的: DOMContentLoaded mdn文档地址:https: ...
- 【linux】mkdir -p命令
如果要创建目录A并创建目录A的子目录B,没有用-p的情况下是mkdir 2次 如果用-p 可以直接创建2个目录 (迭代创建).mkdir -p 目录A/子目录B就可以
- 小米开源监控open-falcon
小米开源监控系统Open-Falcon安装使用笔记 07net01.com 发布于 2016-10-25 18:42:03 分类:IT技术 阅读(88) 评论 前言 近期爆出Zabbix有严重bug, ...
- MySQL建表规范与常见问题 (go)
一. 表设计 库名.表名.字段名必须使用小写字母,“_”分割. 库名.表名.字段名必须不超过12个字符. 库名.表名.字段名见名知意,建议使用名词而不是动词. 建议使用InnoDB存储引擎. 存储精确 ...
- 32位汇编基础_cpu 寄存器
32位通用寄存器 EAX EBX ECX EDX EBP ESP ESI EDI 八个寄存器都可以作为普通的数据寄存器使用.但有的有特殊的用途: EAX 为累加器, ECX 为计数器, E ...
- HDU 4762 Cut the Cake(高精度)
Cut the Cake Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)Tota ...
- [转]命令行在IIS添加虚拟目录
来自:http://www.jb51.net/softjc/29702.htmlMkwebdir -c LocalHost -w "Default Web Site" –v Com ...
- Linux C 一些函数 所属头文件
1. Linux中一些头文件的作用:<assert.h>:ANSI C.提供断言,assert(表达式)<glib.h>:GCC.GTK,GNOME的基础库,提供很多有用的函数 ...
- Fatal error: Call to undefined function Think\C() in /var/www/html/ceshi.hzheee.com/think/ThinkPHP/Library/Think/Think.class.php on line 334 这个问题解决
当APP_DEBUG为true时,包含图中这个文件,文件中又引导包含这些库文件,可以看出安装thinkphp3.2.3时ThinkPHP/Common/下是functions.php,把它改成func ...