ASP.NET的MVC 5 JsonResult缓存 [英] ASP .Net MVC 5 JsonResult caching
问题描述
有人可以解释我如何实现MVC中的应用5 JsonResult
行动缓存?
我想用一些缓存 AJAX
使用 [的OutputCache()]
属性-called行动。其中一些行动返回的ActionResult
与 HTML
-content,有的 JsonResult
与 {ID,标题}
对序列列出了我要用来构造下拉列表。
can someone explain me how to implement caching of JsonResult
actions in MVC 5 application?
I want to use caching of some ajax
-called actions using [OutputCache()]
attribute. Some of these actions return ActionResult
with html
-content, some JsonResult
with serialized lists of {Id, Title}
pairs which I'm going to use to construct dropdown lists.
我的目标是(用ajax-呼唤它时),以降低DB-查询量(同时建设的ViewModels)和服务器的请求。
My goal is to reduce amount of DB-queries (while building ViewModels) and server requests (when using ajax-calls for it).
所以,我的code看起来像下面的代码片段:
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);
}
当我看到Firefox的工具面板我看到 HTML
-content下一张图片:
When I look at FireFox tools-panel I see next picture for Html
-content:
下面Firefox使用 AJAX
-requested页的客户端缓存版本。
Here Firefox uses client-side cached version of ajax
-requested page.
But situation differs with json
-content:
它不缓存的内容,似乎将数据从服务器(服务器端缓存)转移。
It doesn't cache content, and seems to transfer data from server (server-side cache).
在这两种情况下的响应头看起来是一样的:
In both cases response headers look the same:
Cache-Control:"public, max-age=86400, s-maxage=0"
内容是使用类似的要求 AJAX
-calls像
$.get(url, null, function(data){
//do something with data
});
那么,我该怎么办缓存JSON-内容?什么是做正确的方式,为什么默认的方法是行不通的?
So, how do I cache json-content? what is the right way to do it, and why default approach does not work?
推荐答案
如果你想避免数据库查询,你应该考虑在服务器端缓存中的数据。您可以使用的MemoryCache 一>类来做到这一点。
If you want to avoid DB queries, you should consider caching the data at server side. You can use MemoryCache class to do that.
快速样品
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;
}
}
}
您可以更改方法签名来返回你想要的类型。为简单起见,我使用列表&LT;串GT;
You can change the method signature to return the type you want. For simplicity, i am using List<String>
这篇关于ASP.NET的MVC 5 JsonResult缓存的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!