架构师_程序员_码农网

 找回密码
 注册[Register]

QQ登录

只需一步,快速开始

查看: 6685|回复: 1

[WebAPI] ASP.Net Web API 输出缓存Output caching in ASP.NET Web API

[复制链接]
发表于 2019-1-17 16:40:51 | 显示全部楼层 |阅读模式
一.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方法添加相关的缓存键值对并设置缓存过期时间,返回结果。




上一篇:卸载win10冗余应用工具
下一篇:《css世界》张鑫旭著 azw3+mobi+epub
码农网,只发表在实践过程中,遇到的技术难题,不误导他人。
发表于 2019-1-19 09:09:45 | 显示全部楼层
码农网,只发表在实践过程中,遇到的技术难题,不误导他人。
您需要登录后才可以回帖 登录 | 注册[Register]

本版积分规则

免责声明:
码农网所发布的一切软件、编程资料或者文章仅限用于学习和研究目的;不得将上述内容用于商业或者非法用途,否则,一切后果请用户自负。本站信息来自网络,版权争议与本站无关。您必须在下载后的24个小时之内,从您的电脑中彻底删除上述内容。如果您喜欢该程序,请支持正版软件,购买注册,得到更好的正版服务。如有侵权请邮件与我们联系处理。

Mail To:help@itsvse.com

QQ|手机版|小黑屋|架构师 ( 鲁ICP备14021824号-2 )|网站地图

GMT+8, 2024-4-25 08:34

Powered by Discuz! X3.4

Copyright © 2001-2021, Tencent Cloud.

快速回复 返回顶部 返回列表