ASP.Net MVC 5 Caching JsonResult

can someone explain to me how to implement JsonResult action JsonResult in MVC 5 application? I want to use caching of some ajax certified actions using the [OutputCache()] attribute. Some of these actions return an ActionResult with html -content, some JsonResult with serialized lists of pairs {Id, Title} , which I am going to use to create drop-down lists.

My goal is to reduce the number of database queries (when creating ViewModels) and server requests (when using ajax calls for it).

So my code looks like snippets below:

 [OutputCache(Duration=60*60*24)] public async Task<ActionResult> SearchCaseOrgDialog(){ //extract data return html page return View(); } [OutputCache(Duration=60*60*24)] public async Task<JsonResult> AjaxOrgDepartments(){ //query database, serialize data, return json var result = await ctx.OrgDepartments .Select(d => new { Id = d.Id, Title = d.Title } ) .ToListAsync(); return Json(result, JsonRequestBehavior.AllowGet); } 

When I look at the FireFox toolbar, I see the following image for html -content: FF caching html content

Here, Firefox uses the client-side cached version of the ajax -requested page.

But the situation is different from json -content: FF does not cache json contents

It does not cache the contents and, apparently, transfers data from the server (server cache).

In both cases, the response headers look the same:

 Cache-Control:"public, max-age=86400, s-maxage=0" 

Content is requested using similar ajax collections, e.g.

 $.get(url, null, function(data){ //do something with data }); 

So how can I cache json-content? how to do it right and why does the default approach not work?

+7
json ajax caching asp.net-mvc asp.net-mvc-5
source share
2 answers

If you want to avoid database queries, you should consider caching data on the server side. You can use the MemoryCache class to do this.

Quick example

 public class MyLookupDataCache { const string categoryCacheKey = "CATEGORYLIST"; public List<string> GetCategories() { var cache = MemoryCache.Default; var items = cache.Get(categoryCacheKey); if (items != null) { CacheItemPolicy policy = new CacheItemPolicy(); policy.AbsoluteExpiration = DateTime.Now.AddDays(7); //7 days //Now query from db List<string> newItems = repository.GetCategories(); cache.Set(categoryCacheKey, newItems, policy); return newItems; } else { return (List<string>) items; } } } 

You can change the signature of the method to return the desired type. For simplicity, I use List<String>

+2
source share

I had the same issue when trying to cache JSON on the client side, and this is what helped me.

Obs .: For the server side, you can use Runtime Caching or HttpRequest.Cache.

You need to install OutputCache using Client Side Location and VaryByParam with User-Agent.

This will only work for POST, not GET.

Example: download this solution

Act:

 [OutputCache(Duration = 3600, Location = OutputCacheLocation.Client, VaryByParam = "User-Agent")] public JsonResult ListaJson() { var model = new List<string>(); model.Add("item1"); model.Add("item2"); model.Add("item3"); model.Add("item4"); return this.Json(model, JsonRequestBehavior.AllowGet); } 

Look:

 @model string @{ ViewBag.Title = "About"; Layout = "~/Views/Shared/_Layout.cshtml"; } <h2>@this.Model</h2> <div id="id123"></div> <script type="text/javascript"> var url = '@Url.Action("ListaJson", "Home")'; $(document).ready(function(){ $("#id123").load(url); }); </script> 

Result:

enter image description here

0
source share

All Articles