如何在 MVC 应用程序中缓存数据 [英] How to cache data in a MVC application

查看:78
本文介绍了如何在 MVC 应用程序中缓存数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经阅读了很多关于 MVC 应用程序中的页面缓存和部分页面缓存的信息.但是,我想知道您将如何缓存数据.

I have read lots of information about page caching and partial page caching in a MVC application. However, I would like to know how you would cache data.

在我的场景中,我将使用 LINQ to Entities(实体框架).在第一次调用 GetNames(或任何方法)时,我想从数据库中获取数据.我想将结果保存在缓存中,并在第二次调用时使用缓存版本(如果存在).

In my scenario I will be using LINQ to Entities (entity framework). On the first call to GetNames (or whatever the method is) I want to grab the data from the database. I want to save the results in cache and on the second call to use the cached version if it exists.

任何人都可以举例说明这是如何工作的,应该在哪里实现(模型?)以及它是否可行.

Can anyone show an example of how this would work, where this should be implemented (model?) and if it would work.

我已经在传统的 ASP.NET 应用程序中看到过这种情况,通常用于非常静态的数据.

I have seen this done in traditional ASP.NET apps , typically for very static data.

推荐答案

在您的模型中引用 System.Web dll 并使用 System.Web.Caching.Cache

Reference the System.Web dll in your model and use System.Web.Caching.Cache

    public string[] GetNames()
    {
      string[] names = Cache["names"] as string[];
      if(names == null) //not in cache
      {
        names = DB.GetNames();
        Cache["names"] = names;
      }
      return names;
    }

有点简化,但我想这会奏效.这不是特定于 MVC 的,我一直使用这种方法来缓存数据.

A bit simplified but I guess that would work. This is not MVC specific and I have always used this method for caching data.

这篇关于如何在 MVC 应用程序中缓存数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆