出处: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 输出缓存(转)的更多相关文章

  1. 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 ...

  2. ASP.NET Web API实现缓存的2种方式

    在ASP.NET Web API中实现缓存大致有2种思路.一种是通过ETag, 一种是通过类似ASP.NET MVC中的OutputCache. 通过ETag实现缓存 首先安装cachecow.ser ...

  3. 在asp.net web api中利用过滤器设置输出缓存

    介绍 本文将介绍如何在asp.net web api中利用过滤器属性实现缓存. 实现过程 1,首先在web.config文件下appsettings下定义“CacheEnabled”和“CacheTi ...

  4. ASP.NET Web API中通过ETag实现缓存

    通常情况下Server是无状态的,在ASP.NET Web API中,我们可以让服务端响应体中产生ETag属性,起到缓存的作用.大致实现原理是: 1.服务端的响应体中返回一个ETag属性2.客户端通过 ...

  5. ASP.NET Web API通过ActionFilter来实现缓存

    using System; using System.Collections.Generic; using System.Linq; using System.Threading; using Sys ...

  6. 目标HttpController在ASP.NET Web API中是如何被激活的:目标HttpController的创建

    目标HttpController在ASP.NET Web API中是如何被激活的:目标HttpController的创建 通过上面的介绍我们知道利用HttpControllerSelector可以根据 ...

  7. 目标HttpController在ASP.NET Web API中是如何被激活的:目标HttpController的选择

    目标HttpController在ASP.NET Web API中是如何被激活的:目标HttpController的选择 ASP.NET Web API能够根据请求激活目标HttpController ...

  8. 在一个空ASP.NET Web项目上创建一个ASP.NET Web API 2.0应用

    由于ASP.NET Web API具有与ASP.NET MVC类似的编程方式,再加上目前市面上专门介绍ASP.NET Web API 的书籍少之又少(我们看到的相关内容往往是某本介绍ASP.NET M ...

  9. ASP.NET Web API Model-ParameterBinding

    ASP.NET Web API Model-ParameterBinding 前言 通过上个篇幅的学习了解Model绑定的基础知识,然而在ASP.NET Web API中Model绑定功能模块并不是被 ...

随机推荐

  1. i2c接口笔记

    一. i2c基础知识 1. NACK信号:当在第9个时钟脉冲的时候SDA线保持高电平,就被定义为NACK信号.Master要么产生STOP条件来放弃这次传输,或者重复START条件来发起一个新的开始. ...

  2. 第01章-欢迎学习VTK

    [译者:这个系列教程是以Kitware公司出版的<VTK User's Guide -11th edition>一书作的中文翻译(出版时间2010年,ISBN: 978-1-930934- ...

  3. Animation获得当前播放的第几帧

    http://blog.csdn.net/cocos2der/article/details/8728443 http://www.it165.net/pro/html/201405/13204.ht ...

  4. 排列算法(reverse...rotate...next_permutation)

    #include <iostream> #include <algorithm> #include <cstring> using namespace std; i ...

  5. [转]无网络环境,在Windows Server 2008 R2和SQL Server 2008R2环境安装SharePoint2013 RT

    无网络环境,在Windows Server 2008 R2和SQL Server 2008R2环境安装SharePoint2013 RT,这个还有点麻烦,所以记录一下,下次遇到省得绕弯路.进入正题: ...

  6. JSON数组对象某个属性值查找

    1.引用国外开源Linq写法的js框架 地址:https://archive.codeplex.com/?p=jslinq https://www.nuget.org/packages/jslinq ...

  7. 如何制作行政区划矢量图(shp格式)

    详细图文ArcGIS10.2破解版教程地址:http://jingyan.baidu.com/article/e73e26c0cb5c1324adb6a791.html 有时候想要一张shp格式的地方 ...

  8. Oracle VM VirtualBox安裝Windows 2000失败

    问题: VirtualBox下安装Windows2000,设置网络后进入最后一步,复制组件……然后就是重启:再试还是重启!   解决: 在Oracle网站上查了一下资料:http://www.virt ...

  9. oracle 跨库访问

    创建DBLINK的方法: 1. create public database link dblink connect to totalplant identified by totalplant us ...

  10. [Octave] optimset()

    Create options struct for optimization functions. optimset('parameter', value, ...); %设置所有参数及其值,未设置的 ...