WebAPI HttpContext Cache - is it possible?

2020-04-21 05:04发布

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

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.

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.

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?

1条回答
萌系小妹纸
2楼-- · 2020-04-21 05:48

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.

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.

查看更多
登录 后发表回答