【问题标题】:Can I make my ASP.Net WebAPI controller cache its results?我可以让我的 ASP.Net WebAPI 控制器缓存它的结果吗?
【发布时间】:2014-06-10 05:48:50
【问题描述】:

我有像这样的标准 WebAPI 方法。这些方法使用 Entity Framework 6.1 从 SQL Server 2012 数据库中检索数据:

    [ResponseType(typeof(Content))]
    public async Task<IHttpActionResult> Get(int id)
    {
        Content content = await db.Contents.FindAsync(id);
        if (content == null)
        {
            return NotFound();
        }

        return Ok(content);
    }

有没有办法可以缓存响应,这样它就不会每次都访问数据库?

【问题讨论】:

  • 你可以使用.net缓存,我不知道你为什么这么怀疑?
  • 我不怀疑。只是我不知道该怎么做。抱歉,也许我的问题措辞不太好。
  • 如果你在 Azure 上使用 redis 缓存和来自azure.microsoft.com/blog/2014/06/05/…的示例代码

标签: asp.net asp.net-web-api azure-caching


【解决方案1】:

我认为您可能需要使用 ETags(实体标签)。我自己没有尝试过,但thisthat 博客文章可能对您有用。后者还包括许多其他关于缓存的博客文章链接。

【讨论】:

    【解决方案2】:

    你可以这样使用

         if(HttpContext.Current.Cache["myKey"] == null){
                 //Get the data from the database;  
                   HttpContext.Current.Cache["myKey"] = content;
         }else
            return ok((Content)HttpContext.Current.Cache["myKey"]);
    

    由于您的内容可以为 null ,请多保留一个缓存项以跟踪内容是否存在但为 null

            HttpContext.Current.Cache["IsData"] = content == null ? false : true;
    

    现在就这样做

                if(HttpContext.Current.Cache["IsData"] == null){
                 //Get the data from the database; 
                  HttpContext.Current.Cache["IsData"] = content == null ? false : true; 
                  if(content != null){
                   HttpContext.Current.Cache["myKey"] = content;
    
                }
         }  else
            return HttpContext.Current.Cache["myKey"] != null ? ok((Content)HttpContext.Current.Cache["myKey"]) : NotFound();;
    

    此逻辑适用于您将要使用的任何类型的缓存。

    【讨论】:

    • 为了便于理解,您能否告诉我这如何适合我的问题中的控制器方法示例。谢谢。
    • @devesh:所以,假设我理解正确,如果数据库中的内容发生更改您缓存它之后会发生什么?我认为您将始终获得最初缓存的内容,因此您会错过对其所做的任何更改。我不确定您的示例如何处理这种情况。也许我错了,如果你能解释一下就好了。
    猜你喜欢
    • 1970-01-01
    • 2011-03-26
    • 1970-01-01
    • 2020-04-30
    • 2011-07-15
    • 2013-08-31
    • 2013-12-30
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多