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?