WebAPI HttpContext 缓存 - 有可能吗?

Rob*_*ous 2 asp.net-mvc caching asp.net-mvc-4 asp.net-web-api

我在常规 MVC 控制器中执行了以下操作:

public ActionResult GetCourses()
{
  List<Course> courses = new List<Course>();

  if (this.HttpContext.Cache["courses"] == null)
  {
    courses = _db.Courses.ToList();
    this.HttpContext.Cache["courses"] = courses;
  }
  else
  {
    courses = (List<Course>)this.HttpContext.Cache["courses"];
  }

  return PartialView("_Courses", courses);
}
Run Code Online (Sandbox Code Playgroud)

我缓存的原因是因为课程在两个位置加载 - 用于选择课程的模式和列出所有课程的索引视图。该模式仅需要 JSON 来渲染(从 WebAPI 中提取数据),而索引视图是 Razor 生成的视图(通过 MVC 控制器提取)。

如果我已经有了课程数据,我会尝试不再查询数据库。

上面的代码适用于索引视图。现在,对于模态,我只需要发送 JSON,但前提是课程尚未加载到索引视图中。

我尝试从 API 控制器访问 HttpContext,但似乎无法以相同的方式访问它。 如何从 WebAPI 控制器检查 HttpContext.Cache,并在需要时填充它,以便 MVC 控制器可以检查其内容?

Bad*_*dri 5

您可以像这样从 Web API 控制器设置缓存。

var context = HttpContext.Current;

if (context != null)
{
    if (context.Cache["courses"] == null)
    {
        context.Cache["courses"] = _db.Courses.ToList();
    }
}
Run Code Online (Sandbox Code Playgroud)

为了简单起见,我在这里没有使用任何锁定。如果你的应用程序并发量较高,最好在设置缓存的同时实现锁。

此外,为了让 MVC 读取 We API 设置的缓存,您的 Web API 和 MVC 控制器必须属于同一应用程序。只是陈述显而易见的事情。