zoukankan      html  css  js  c++  java
  • 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实现缓存"中也做了总结。

  • 相关阅读:
    git 使用 VisualStudio 比较分支更改
    Java实现 LeetCode 264 丑数 II(二)
    PHP error_log() 函数
    PHP error_get_last() 函数
    PHP debug_print_backtrace() 函数
    PHP debug_backtrace() 函数
    PHP scandir() 函数
    复制相关参数学习笔记--master上的参数
    OI生涯回忆录 2018.11.12~2019.4.15
    C# 金额转中文大写
  • 原文地址:https://www.cnblogs.com/darrenji/p/5150277.html
Copyright © 2011-2022 走看看