本文介绍了WebAPI HttpContext缓存-有可能​​吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在常规的MVC控制器中完成了以下操作:

I've done the following in my regular MVC controller:

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);
}

我缓存的原因是因为课程在两个地方加载-选择课程的模式和列出所有课程的索引视图.模态只需要JSON即可呈现(从WebAPI中提取数据),而索引"视图是Razor生成的视图(通过MVC控制器拉出).

The reason I'm caching is because Courses are loaded in two places - a Modal to select a Course, and an Index view that lists all courses. The modal only requires JSON to render (pull data from WebAPI), whereas the Index view is a Razor-generated view (pulled via MVC controller).

如果我已经有了课程"数据,我将尝试不再次查询数据库.

I'm trying not to query the db again if I already have the Courses data.

上面的代码用于Index视图.现在,对于Modal,我只需要发送JSON,但前提是尚未在Index视图中加载课程.

The above code is for the Index view. Now, for the Modal, I need to send only JSON, but only if courses haven't already been loaded in the Index view.

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

I tried accessing HttpContext from an API controller but it doesn't seem to be accessible in the same manner. How can I check the HttpContext.Cache from a WebAPI controller, and populate it if need be so that the MVC controller can check its contents?

推荐答案

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

You can set the cache from Web API controller like this.

var context = HttpContext.Current;

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

为简单起见,我在这里不使用任何锁定.如果您的应用程序具有高并发性,则最好在设置缓存时实现锁定.

For the sake of simplicity, I'm not using any locking here. If your application has high concurrency, it is better to implement a lock while setting the cache.

此外,为了使We API设置的缓存被MVC读取,您的Web API和MVC控制器必须属于同一应用程序.只是说明显而易见的内容.

Also, in order for the cache set by We API to be read by MVC, your Web API and MVC controllers must be part of the same application. Just stating the obvious.

这篇关于WebAPI HttpContext缓存-有可能​​吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-06 20:10