在ASP.NET Web API中实现缓存大体有2种思路。一种是经过ETag, 一种是经过相似ASP.NET MVC中的OutputCache。
经过ETag实现缓存
首先安装cachecow.server
install-package cachecow.server
在WebApiConfig中。html
public static class WebApiConfig { public static HttpConfiguraiton Register() { var config = new HttpConfiguration(); //支持经过特性设置路由 config.MapHttpAttributeRoutes(); config.Routes.MapHttpRoute( "DefaultRouting", "api/{controller}/{id}", defaults:new {id = RouteParamter.Optional} ); //config.Formatters.JsonFormatter.SupportedMediaTypes .Add(new MediaTYpeHeaderValue("text/html")); config.Formatters.XmlFormatter.SupportedMediaType.Clear(); config.Foramtters.JsonFormatter.SuppoortedMediaTypes.Add( new MediaTypeHeaderValue("application/json-patch+json"); ); config.Formatters.JsonFormatter.SerializerSettings.Formatting = Newtonsoft.Json.Formatting.Indented; config.Formatters.JsonFormatter.SerializerSettings.ContractResolver = new CamelCaseProeprtyNamesContractResolver(); //HTTP缓存 默认缓存在内存中 config.MessageHandlers.Add(new CacheCow.Server.CachingHandler(config)); return config; } }
→ 客户端发出请求
GET http://localhost:43321/api/groups/1
→ 返回200状态码,在响应的Headers中:
ETag:W/"..."
Last-Modified:...
→ 再次请求,经过If-None-Match属性把ETag带上。
GET http://localhost:43321/api/groups/1
Host:localhost:43321
If-None-Match:ETag:W/""
→ 返回304状态码
经过OutputCache实现缓存
在ASP.NET Web API中实现缓存的另一种思路是经过相似ASP.NET MVC中的OutputCache,具体可参考:Strathweb.CacheOutput.WebApi2
有关ASP.NET Web API缓存,在"ASP.NET Web API中经过ETag实现缓存"中也作了总结。
web