ASP.NET Web API通过ActionFilter来实现缓存
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using System.Web;
using System.Web.Caching;
using System.Web.Http;
using System.Web.Http.Controllers;
using System.Web.Http.Filters; namespace WebApi
{
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method)]
public class CacheAttribute : ActionFilterAttribute
{
public string AbsoluteExpiration { get; set; }
public string SlidingExpiration { get; set; }
public CacheItemPriority Priority { get; set; } public CacheAttribute()
{
Priority = CacheItemPriority.Normal;
} public override void OnActionExecuting(HttpActionContext actionContext)
{
var actionDescriptor = actionContext.ActionDescriptor as ReflectedHttpActionDescriptor;
if (null == actionDescriptor)
{
base.OnActionExecuting(actionContext);
}
var key = new CacheKey(actionDescriptor.MethodInfo, actionContext.ActionArguments);
var array = HttpRuntime.Cache.Get(key.ToString()) as object[];
if (null == array)
{
base.OnActionExecuting(actionContext);
return;
}
var value = array.Any() ? array[] : null;
var actionResult = value as IHttpActionResult;
if (null != actionResult)
{
actionContext.Response = actionResult.ExecuteAsync(CancellationToken.None).Result;
return;
}
actionContext.Response = actionDescriptor.ResultConverter.Convert(actionContext.ControllerContext, value);
}
} public class CacheableActionDescriptor : ReflectedHttpActionDescriptor
{
private CacheAttribute CacheAttribute { get; } public CacheableActionDescriptor(ReflectedHttpActionDescriptor actionDescriptor, CacheAttribute cacheAttribute) : base(actionDescriptor.ControllerDescriptor, actionDescriptor.MethodInfo)
{
CacheAttribute = cacheAttribute;
} public override Task<object> ExecuteAsync(HttpControllerContext controllerContext, IDictionary<string, object> arguments, CancellationToken cancellationToken)
{
var absoluteExpiration = Cache.NoAbsoluteExpiration;
var slidingExpiration = Cache.NoSlidingExpiration;
var priority = CacheAttribute.Priority;
if (!string.IsNullOrWhiteSpace(CacheAttribute.AbsoluteExpiration))
{
absoluteExpiration = DateTime.Now + TimeSpan.Parse(CacheAttribute.AbsoluteExpiration);
}
if (!string.IsNullOrWhiteSpace(CacheAttribute.SlidingExpiration))
{
slidingExpiration = TimeSpan.Parse(CacheAttribute.SlidingExpiration);
}
var cacheKey = new CacheKey(MethodInfo, arguments);
var result = base.ExecuteAsync(controllerContext, arguments, cancellationToken).Result;
HttpRuntime.Cache.Insert(cacheKey.ToString(), new[] {result}, null, absoluteExpiration, slidingExpiration, priority, null);
return Task.FromResult(result);
}
} public class CacheableActionSelector : ApiControllerActionSelector
{
public override HttpActionDescriptor SelectAction(HttpControllerContext controllerContext)
{
var actionDescriptor = base.SelectAction(controllerContext);
var reflectedActionDescriptor = actionDescriptor as ReflectedHttpActionDescriptor;
if (null == reflectedActionDescriptor)
{
return actionDescriptor;
}
var cacheAttribute = reflectedActionDescriptor.GetCustomAttributes<CacheAttribute>().FirstOrDefault() ??
reflectedActionDescriptor.ControllerDescriptor.GetCustomAttributes<CacheAttribute>().FirstOrDefault();
if (null == cacheAttribute)
{
return actionDescriptor;
}
return new CacheableActionDescriptor(reflectedActionDescriptor, cacheAttribute);
}
}
}
注册ActionSelector
using System;
using System.Web;
using System.Web.Http;
using System.Web.Http.Controllers;
using WebApi; namespace WebHost
{
public class Global : HttpApplication
{
protected void Application_Start(object sender, EventArgs e)
{
// 注册ASP.NET Web API路由
GlobalConfiguration.Configuration.Routes.MapHttpRoute("default", "api/{controller}/{id}", new { id = RouteParameter.Optional }); // 注册CacheableActionSelector
GlobalConfiguration.Configuration.Services.Replace(typeof(IHttpActionSelector), new CacheableActionSelector());
}
}
}
使用CacheAttribute
public class DemoController : ApiController
{
[Cache(AbsoluteExpiration = "00:00:02", SlidingExpiration = "", Priority = CacheItemPriority.High)]
public DateTime Get()
{
return DateTime.Now;
}
}
ASP.NET Web API通过ActionFilter来实现缓存的更多相关文章
- ASP.NET Web API中通过ETag实现缓存
通常情况下Server是无状态的,在ASP.NET Web API中,我们可以让服务端响应体中产生ETag属性,起到缓存的作用.大致实现原理是: 1.服务端的响应体中返回一个ETag属性2.客户端通过 ...
- ASP.NET Web Api 使用CacheCow和ETag缓存资源(转载)
转载地址:http://www.cnblogs.com/fzrain/p/3618887.html 前言 本文将使用一个开源框架CacheCow来实现针对Http请求资源缓存,本文主要介绍服务器端的缓 ...
- ASP.NET Web API实现缓存的2种方式
在ASP.NET Web API中实现缓存大致有2种思路.一种是通过ETag, 一种是通过类似ASP.NET MVC中的OutputCache. 通过ETag实现缓存 首先安装cachecow.ser ...
- 8 种提升 ASP.NET Web API 性能的方法
ASP.NET Web API 是非常棒的技术.编写 Web API 十分容易,以致于很多开发者没有在应用程序结构设计上花时间来获得很好的执行性能. 在本文中,我将介绍8项提高 ASP.NET Web ...
- 通过扩展让ASP.NET Web API支持W3C的CORS规范
让ASP.NET Web API支持JSONP和W3C的CORS规范是解决"跨域资源共享"的两种途径,在<通过扩展让ASP.NET Web API支持JSONP>中我们 ...
- 新作《ASP.NET Web API 2框架揭秘》正式出版
我觉得大部分人都是“眼球动物“,他们关注的往往都是目光所及的东西.对于很多软件从业者来说,他们对看得见(具有UI界面)的应用抱有极大的热忱,但是对背后支撑整个应用的服务却显得较为冷漠.如果我们将整个“ ...
- 如何让ASP.NET Web API的Action方法在希望的Culture下执行
在今天编辑推荐的<Hello Web API系列教程--Web API与国际化>一文中,作者通过自定义的HttpMessageHandler的方式根据请求的Accep-Language报头 ...
- ASP.NET Web API 提升性能的方法实践
ASP.NET Web API 是非常棒的技术.编写 Web API 十分容易,以致于很多开发者没有在应用程序结构设计上花时间来获得很好的执行性能. 在本文中,我将介绍8项提高 ASP.NET Web ...
- ASP.NET Web API 应用教程(一) ——数据流使用
相信已经有很多文章来介绍ASP.Net Web API 技术,本系列文章主要介绍如何使用数据流,HTTPS,以及可扩展的Web API 方面的技术,系列文章主要有三篇内容. 主要内容如下: I 数据 ...
随机推荐
- android私有文件夹的访问
首先内部存储路径为/data/data/youPackageName/,下面讲解的各路径都是基于你自己的应用的内部存储路径下. 所有内部存储中保存的文件在用户卸载应用的时候会被删除. 一. files ...
- wireshark解密本地https流量笔记
此方式支持firefox,chrome 建立path变量 SSLKEYLOGFILE=c:\ssl.key 重启firefox chrome,访问https网站会自动生成ssl session key ...
- Qt的零碎知识
1.QObject是所有Qt对象的基类,他给C++的类带来了若干新的功能.使用Q_OBJECT宏能声明一个C++类为一个QObject.如: class Notepad : public QMainW ...
- [转]Handy adb commands for Android
转自:http://www.growingwiththeweb.com/2014/01/handy-adb-commands-for-android.html View connected devic ...
- [LeetCode] Combination Sum 回溯
Given a set of candidate numbers (C) and a target number (T), find all unique combinations in C wher ...
- ASP.NET服务器控件使用之Reportviewer 报表
http://blog.csdn.net/oemoon/article/details/7338967 http://www.cnblogs.com/emanlee/archive/2008/09/1 ...
- SNF开发平台WinForm之三-开发-单表选择控件创建-SNF快速开发平台3.3-Spring.Net.Framework
3.1运行效果: 3.2开发实现: 3.2.1 这个开发与第一个开发操作步骤是一致的,不同之处就是在生成完代码之后,留下如下圈红程序,其它删除. 第一个开发地址:开发-单表表格编辑管理页面 http: ...
- 红黑树(二)之 C语言的实现
概要 红黑树在日常的使用中比较常用,例如Java的TreeMap和TreeSet,C++的STL,以及Linux内核中都有用到.之前写过一篇文章专门介绍红黑树的理论知识,本文将给出红黑数的C语言的实现 ...
- 【转载】Linux下编辑生成.mo文件
转载自:http://www.hackbase.com/tech/2012-02-27/65972.html 编辑生成.mo文件 我们在弄网站的时候很可能会接触到.mo和.po文件..po文件是GNU ...
- SQL Server中的事务日志管理(6/9):大容量日志恢复模式里的日志管理
当一切正常时,没有必要特别留意什么是事务日志,它是如何工作的.你只要确保每个数据库都有正确的备份.当出现问题时,事务日志的理解对于采取修正操作是重要的,尤其在需要紧急恢复数据库到指定点时.这系列文章会 ...