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

时间:2023-03-09 01:32:27
ASP.NET Web API实现缓存的2种方式

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

通过ETag实现缓存

首先安装cachecow.server

install-package cachecow.server

在WebApiConfig中。

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实现缓存"中也做了总结。