C# 如何在 ASP.NET Web API 中使用缓存?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14811772/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-10 13:04:24  来源:igfitidea点击:

How to use caching in ASP.NET Web API?

c#asp.net-web-apihttp-caching

提问by Yasser Shaikh

I am using ASP.NET MVC 4 with WEB API

我正在使用 ASP.NET MVC 4 和 WEB API

I have the following action, in the action shown below, my service method makes a db call to DoMagic()method and returns an integer value which I am then using on every page, this action is called using an ajax call.

我有以下操作,在下面显示的操作中,我的服务方法对方法进行 db 调用DoMagic()并返回一个整数值,然后我在每个页面上使用该值,使用 ajax 调用调用此操作。

Below is my WEB API action :

以下是我的 WEB API 操作:

[OutputCache(Duration = 86400, VaryByParam = "none")]
[ActionName("GetMyMagicNumber")]
public int GetMyMagicNumber()
{
    if (WebSecurity.IsAuthenticated)
    {
        var revenue = _magicService.DoMagic();
        return revenue;
    }
    return 0;
}

My question : I haved tried using [OutputCache(Duration = 86400, VaryByParam = "none")]and I excepted that only the first time the db call will be made and next subsequent request to this action will return me the cached value, but this is not happening.

我的问题:我已经尝试过使用[OutputCache(Duration = 86400, VaryByParam = "none")],但我排除了只有第一次进行 db 调用并且对该操作的下一个后续请求将返回缓存值的情况,但这并没有发生。

A db call is again made, the db call takes time how do I get this working ?

数据库调用再次进行,数据库调用需要时间我如何让它工作?

采纳答案by OakNinja

Unfortunately, caching is not built into ASP.NET Web API.

不幸的是,缓存没有内置到 ASP.NET Web API 中。

Check this out to get you on track: http://www.strathweb.com/2012/05/output-caching-in-asp-net-web-api/

看看这个让你走上正轨:http: //www.strathweb.com/2012/05/output-caching-in-asp-net-web-api/

An updated resource here: https://github.com/filipw/AspNetWebApi-OutputCache

此处更新资源:https: //github.com/filipw/AspNetWebApi-OutputCache

EDIT: As of 2020-02-03, even though this answer is quite old, it's still valid.

编辑:截至 2020 年 2 月 3 日,即使这个答案很旧,它仍然有效。

Both of the URL's above lead to the same project, ASP.NET Web API CacheOutputby Filip W

两者的URL的上方通向同一个项目,ASP.NET的Web API CacheOutput菲利普W ^

回答by CodeZombie

As already mentioned by OakNinja, output caching via [OutputCache]attributes is currently not supported by the ASP.NET Web API.

正如 OakNinja 已经提到的,[OutputCache]ASP.NET Web API 目前不支持通过属性进行输出缓存。

However, there are a few open source implementations filling the gap:

但是,有一些开源实现填补了这一空白:

Strathweb.CacheOutput

Strathweb.CacheOutput

A small library bringing caching options, similar to MVC's "OutputCacheAttribute", to Web API actions.

一个小型库,为 Web API 操作带来缓存选项,类似于 MVC 的“OutputCacheAttribute”。

Github: https://github.com/filipw/Strathweb.CacheOutput
License: Apache v2

Github:https: //github.com/filipw/Strathweb.CacheOutput
许可证:Apache v2

CacheCow

缓存牛

An implementation of HTTP Caching in ASP.NET Web API for both client-side and server-side.

在 ASP.NET Web API 中为客户端和服务器端实现 HTTP 缓存。

Github: https://github.com/aliostad/CacheCow
License: MIT

Github:https: //github.com/aliostad/CacheCow
许可证:MIT

Note: According to the projects README, the library does not support attribute routing:

注意:根据项目 README,该库不支持属性路由

Currently CacheCow's attribute setting does not work with Attribute Routing. And I personally think you should not use Attribute Routing... (Source: https://github.com/aliostad/CacheCow/blob/master/README.md)

当前 CacheCow 的属性设置不适用于属性路由。而且我个人认为你不应该使用属性路由......(来源:https: //github.com/aliostad/CacheCow/blob/master/README.md

There is a nice blog post by Scott Hanselmanncovering both feature sets.

Scott Hanselmann有一篇很好的博客文章,涵盖了这两个功能集。

回答by wonster

[ResponseCache]is now supported in ASP.NET Core

[ResponseCache]现在在 ASP.NET Core 中受支持

Features may look identical to [OutputCache]but [ResponseCache]is only for the client side.

功能可能看起来相同,[OutputCache][ResponseCache]仅适用于客户端。

Response caching adds cache-related headers to responses. These headers specify how you want client, proxy and middleware to cache responses.

响应缓存将与缓存相关的标头添加到响应中。这些标头指定您希望客户端、代理和中间件如何缓存响应。

https://docs.microsoft.com/en-us/aspnet/core/performance/caching/response

https://docs.microsoft.com/en-us/aspnet/core/performance/caching/response

[ResponseCache(Duration = 3600)]
[HttpGet]
public IEnumerable<Product> Get()
{
  return _service.GetAll();
}

回答by Sagi

Add a reference to System.Runtime.Caching in your project. Add a helper class :

在您的项目中添加对 System.Runtime.Caching 的引用。添加一个辅助类:

using System;
using System.Runtime.Caching;


public static class MemoryCacher
{
    public static object GetValue(string key)
    {
        MemoryCache memoryCache = MemoryCache.Default;
        return memoryCache.Get(key);
    }

    public static bool Add(string key, object value, DateTimeOffset absExpiration)
    {
        MemoryCache memoryCache = MemoryCache.Default;
        return memoryCache.Add(key, value, absExpiration);
    }

    public static  void Delete(string key)
    {
        MemoryCache memoryCache = MemoryCache.Default;
        if (memoryCache.Contains(key))
        {
            memoryCache.Remove(key);
        }
    }
}

Then from your code get or set objects in the cache :

然后从您的代码获取或设置缓存中的对象:

list = (List <ChapterEx>)MemoryCacher.GetValue("CacheItem1");

and

MemoryCacher.Add("CacheItem1", list, DateTimeOffset.UtcNow.AddYears(1));