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绑定功能模块并不是被 ...
随机推荐
- 文档内容类似项处理-Shingling
版权声明:本文为博主原创文章,未经博主同意不得转载. https://blog.csdn.net/jituotianxia2009/article/details/25339807 集合的Jaccar ...
- socket编程---SCTP
sctp_sndrcvinfo结构体 sctp_event_subscribe结构体 更多的关于SCTP的结构体http://aisxyz.iteye.com/blog/2408978 SCTP套接字 ...
- centos 7 安装rabbitmq 3.6.12
0 安装 epel yum -y install http://dl.fedoraproject.org/pub/epel/7/x86_64/Packages/e/epel-release-7-11. ...
- jdk版本对应数字
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'org.springfr ...
- linux(centOs)下memcached安装
1.libevent安装.为啥先安装它?因为不先装,memcached这座房子就没打地基: yum install libevent-devel 敲回车后出现: Loaded plugins: fas ...
- 插入排序算法-python实现
#-*- coding: UTF-8 -*- import numpy as np def InsertSort(a): for i in xrange(1,a.size): for j in xra ...
- 转转转--Java File和byte数据之间的转换
package cn.iworker.file; import java.io.BufferedOutputStream; import java.io.ByteArrayOutputStream; ...
- python 主要模块和方法
******************** PY核心模块方法 ******************** os模块: os.remove() 删除文件 os.unlink() 删除文件 os.rename ...
- django框架 input 文本框 单选框 多选框 上传文件 等数据传输后台的程序 request.getlist接收多个结果 obj.chunks 用于文件传输 enctype="multipart/form-data文件传输必备表头
在上一个博客中,我们学习了如果创建django,这里我们主要讲如何把数据传给后台 在url文件中, 从app01中导入views, 以及创建url(r'^login/', views.login) f ...
- 【322】python控制键盘鼠标:pynput
参考:python实战===python控制键盘鼠标:pynput 参考:[Python Study Notes]pynput实现对鼠标控制 参考:pynput doc 参考:pynput Packa ...