【问题标题】:WebAPI HttpContext Cache - is it possible?WebAPI HttpContext Cache - 有可能吗?
【发布时间】:2013-09-25 05:06:50
【问题描述】:

我在常规 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);
}

我缓存的原因是因为课程加载在两个地方 - 一个用于选择课程的模式和一个列出所有课程的索引视图。 modal 只需要 JSON 来呈现(从 WebAPI 拉数据),而 Index 视图是 Razor 生成的视图(通过 MVC 控制器拉)。

如果我已经拥有 Courses 数据,我会尝试不再查询数据库。

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

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

【问题讨论】:

标签: asp.net-mvc asp.net-mvc-4 caching asp.net-web-api


【解决方案1】:

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

var context = HttpContext.Current;

if (context != null)
{
    if (context.Cache["courses"] == null)
    {
        context.Cache["courses"] = _db.Courses.ToList();
    }
}

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

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

【讨论】:

  • 总是来救我的巴德里。你几乎是我的代理导师 :) 谢谢!
  • 很高兴我能提供帮助。
  • 这在自托管的 Web API 中不起作用。不会有任何HttpContext
猜你喜欢
  • 2010-11-09
  • 2016-01-30
  • 1970-01-01
  • 2015-09-07
  • 2019-04-27
  • 2017-04-20
  • 2012-05-09
  • 2016-09-26
  • 2013-11-20
相关资源
最近更新 更多