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

本文介绍了在ASP.NET Web API中实现缓存的两种主要方法:通过ETag和OutputCache。通过ETag实现缓存涉及使用cachecow.server包,并在WebApiConfig中配置HTTP缓存。而OutputCache类似于ASP.NET MVC中的实现方式。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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

 


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值