一.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的更多相关文章

  1. ASP.Net 更新页面输出缓存的几种方法

    ASP.Net 自带的缓存机制对于提高页面性能有至关重要的作用,另一方面,缓存的使用也会造成信息更新的延迟.如何快速更新缓存数据,有时成了困扰程序员的难题.根据我的使用经验,总结了下面几种方法,概括了 ...

  2. ASP.NET Core中的缓存[1]:如何在一个ASP.NET Core应用中使用缓存

    .NET Core针对缓存提供了很好的支持 ,我们不仅可以选择将数据缓存在应用进程自身的内存中,还可以采用分布式的形式将缓存数据存储在一个“中心数据库”中.对于分布式缓存,.NET Core提供了针对 ...

  3. ASP.Net Web API 输出缓存(转)

    出处:http://www.cnblogs.com/ajilisiwei/p/6112078.html 原文的转载地址:http://www.strathweb.com/2012/05/output- ...

  4. 【转载】IIS与asp.net管道

    阅读目录 asp.net是什么 HTTP协议 IIS与asp.net asp.net管道 参考资料 我们在基于asp.net开发web程序,基本上都是发布部署到安装了IIS的windows服务器上,然 ...

  5. [转载]8 种提升 ASP.NET Web API 性能的方法

    http://www.oschina.net/translate/8-ways-improve-asp-net-web-api-performance 英文原文:8 ways to improve A ...

  6. [转]在ASP.NET WebAPI 中使用缓存【Redis】

    初步看了下CacheCow与OutputCache,感觉还是CacheOutput比较符合自己的要求,使用也很简单 PM>Install-Package Strathweb.CacheOutpu ...

  7. 在ASP.NET WebAPI 中使用缓存【Redis】

    初步看了下CacheCow与OutputCache,感觉还是CacheOutput比较符合自己的要求,使用也很简单 PM>Install-Package Strathweb.CacheOutpu ...

  8. 输出缓存与CachePanel

    缓存的级别 缓存的作用自不必说,提高系统性能最重要的手段之一.上至应用框架,下至文件系统乃至CPU,计算机中各部分设计都能见到缓存的身影.许多朋友一直在追求如何提高Web应用程序的性能,其实最容易被理 ...

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

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

随机推荐

  1. Android Lifecycle使用

    引言 Lifecycle 是官方提供的架构组件之一,目前已经是稳定版本,Lifecycle 组件包括LifecycleOwner.LifecycleObserver.Lifecycle 组件是执行操作 ...

  2. JVM内存区域划分Eden Space,Survivor Space,Tenured Gen,Perm Gen

    jvm区域总体分两类,heap区和非heap区.heap区又分:Eden Space(伊甸园).Survivor Space(幸存者区).Tenured Gen(老年代-养老区). 非heap区又分: ...

  3. Tomcat启动时项目重复加载,导致资源初始化两次!

    一.现象: 每次启动Tomcat 的时候,工程会被加载两次 二.原因: 在tomcat/conf/server.xml配置虚拟目录引起,如下配置: 我们在Host标签里配置了appBase=" ...

  4. 清除float影响

    条件: 父元素中有子元素float的话,可能就会影响父元素的高度,从而影响布局: 解决方案: 1.直接给父元素定高: 弊端:必须知道父元素的高: 2. 父元素使用overflow属性值为hidden解 ...

  5. phpstudy 产生You don't have permission to access / on this server.解决

    phpstudy配置好访问目录时候有时候会产生You don't have permission to access / on this server. 解决办法: 修改服务器httpd.conf配置 ...

  6. C# 任务 数据加载不影响其他操作

    private void button1_Click(object sender, EventArgs e) { //this.timer1.Enabled = true; Task t1 = new ...

  7. vue 构建项目 文件引入

    1.vue引用依赖文件.  举例:axios 先安装 axios.如果直接安装 vue-axios 会报错 npm install axios npm install --save axios vue ...

  8. View体系第一篇:基础

    View体系的学习内容为学习刘望舒先生博客总结的内容,大家可到他的博客看到更详细的内容. 一.view之间的继承关系 Viewground用来包裹其他view.在平常的使用中,我们不会直接用到View ...

  9. Flutter 布局(四)- Baseline、FractionallySizedBox、IntrinsicHeight、IntrinsicWidth详解

    本文主要介绍Flutter布局中的Baseline.FractionallySizedBox.IntrinsicHeight.IntrinsicWidth四种控件,详细介绍了其布局行为以及使用场景,并 ...

  10. Appium+java 模拟键盘输入

    功能键   KEYCODE_CALL 拨号键 5 KEYCODE_ENDCALL 挂机键 6 KEYCODE_HOME 按键Home 3 KEYCODE_MENU 菜单键 82 KEYCODE_BAC ...