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 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 输出缓存 转载 -- Output caching in ASP.NET Web API的更多相关文章
- ASP.Net 更新页面输出缓存的几种方法
ASP.Net 自带的缓存机制对于提高页面性能有至关重要的作用,另一方面,缓存的使用也会造成信息更新的延迟.如何快速更新缓存数据,有时成了困扰程序员的难题.根据我的使用经验,总结了下面几种方法,概括了 ...
- ASP.NET Core中的缓存[1]:如何在一个ASP.NET Core应用中使用缓存
.NET Core针对缓存提供了很好的支持 ,我们不仅可以选择将数据缓存在应用进程自身的内存中,还可以采用分布式的形式将缓存数据存储在一个“中心数据库”中.对于分布式缓存,.NET Core提供了针对 ...
- ASP.Net Web API 输出缓存(转)
出处:http://www.cnblogs.com/ajilisiwei/p/6112078.html 原文的转载地址:http://www.strathweb.com/2012/05/output- ...
- 【转载】IIS与asp.net管道
阅读目录 asp.net是什么 HTTP协议 IIS与asp.net asp.net管道 参考资料 我们在基于asp.net开发web程序,基本上都是发布部署到安装了IIS的windows服务器上,然 ...
- [转载]8 种提升 ASP.NET Web API 性能的方法
http://www.oschina.net/translate/8-ways-improve-asp-net-web-api-performance 英文原文:8 ways to improve A ...
- [转]在ASP.NET WebAPI 中使用缓存【Redis】
初步看了下CacheCow与OutputCache,感觉还是CacheOutput比较符合自己的要求,使用也很简单 PM>Install-Package Strathweb.CacheOutpu ...
- 在ASP.NET WebAPI 中使用缓存【Redis】
初步看了下CacheCow与OutputCache,感觉还是CacheOutput比较符合自己的要求,使用也很简单 PM>Install-Package Strathweb.CacheOutpu ...
- 输出缓存与CachePanel
缓存的级别 缓存的作用自不必说,提高系统性能最重要的手段之一.上至应用框架,下至文件系统乃至CPU,计算机中各部分设计都能见到缓存的身影.许多朋友一直在追求如何提高Web应用程序的性能,其实最容易被理 ...
- 在asp.net web api中利用过滤器设置输出缓存
介绍 本文将介绍如何在asp.net web api中利用过滤器属性实现缓存. 实现过程 1,首先在web.config文件下appsettings下定义“CacheEnabled”和“CacheTi ...
随机推荐
- 史上最全python面试题详解 (二)(附带详细答案(关注、持续更新))
23.re的match和search区别? re.match()从开头开始匹配string. re.search()从anywhere 来匹配string. # 多行模式>>> re ...
- angular select 默认值
<select ng-model="selected" ng-options="x.id as x.name for x in users">< ...
- phpcms有二级导航并且高亮效果代码
<div class="collapse navbar-collapse" id="example-navbar-collapse"> <ul ...
- 你用过CSS3的这个currentColor新属性吗?使用与兼容性
currentColor顾名思意就是“当前颜色”,准确讲应该是“当前的文字颜色”,例如: .xxx { border: 1px solid currentColor; } currentColor表示 ...
- RabbitMQ 消息流程、AMOP 概念
AMOP Server:Broker.RabbitMQ Server,实现 AMOP 实体服务,接受客户端的连接 Conneciton:链接,应用程序与 Server 的网络连接 Channel:网络 ...
- 通过 python ssh库连接并发送命令给设备
import paramiko import time hostname = '192.168.248.156' port = 22 user = 'zhou' passwd = ' paramiko ...
- echarts雷达图点击事件 包含(2.x,3.85,4.02)测试
最近看见别人问的问题,点击雷达图的拐点,获取点击数据的问题,直接上代码. echarts 2x 的点击事件 echarts配置问题:https://www.douban.com/note/509404 ...
- SSL里的certificate格式资料小结
在查看相关报文的时候,发现RFC5246本身并没有对certificate的格式AlgorithmIdentifier作深入的介绍,只说其格式必须是X509v3 DER表示,思虑良久才找到方向:后者的 ...
- MySQL 5.7忘记root密码如何修改?
一直以来,MySQL的应用和学习环境都是MySQL 5.6和之前的版本,也没有去关注新版本MySQL 5.7的变化和新特性.今天帮人处理忘记root密码的时时候,发现以前的方法不奏效了.具体情况如下所 ...
- Markdonw基本语法学习
Markdonw基本语法 二级标题 三级标题 ----ctrl+r 粗体 ctrl+b 斜体 ctr+i #include<stdio.h> void main() { printf(&q ...