gpt4 book ai didi

json - ASP .Net MVC 5 JsonResult 缓存

转载 作者:行者123 更新时间:2023-12-01 20:04:06 27 4
gpt4 key购买 nike

有人可以解释一下如何在 MVC 5 应用程序中实现 JsonResult 操作的缓存吗?我想使用 [OutputCache()] 属性来缓存一些 ajax 调用的操作。其中一些操作返回带有 html 内容的 ActionResult,一些 JsonResult 带有 {Id, Title} 序列化列表我将使用它们来构造下拉列表。

我的目标是减少数据库查询量(在构建 ViewModel 时)和服务器请求量(在使用 ajax 调用时)。

所以,我的代码如下所示:

[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 内容的下一张图片: FF caching html content

此处 Firefox 使用 ajax 请求页面的客户端缓存版本。

但是情况与 json-content 不同: FF doesn't cache json content

它不缓存内容,并且似乎从服务器传输数据(服务器端缓存)。

在这两种情况下,响应 header 看起来相同:

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

使用类似的ajax调用来请求内容

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

那么,如何缓存 json-content?什么是正确的方法,为什么默认方法不起作用?

最佳答案

如果你想避免数据库查询,你应该考虑在服务器端缓存数据。您可以使用MemoryCache类来做到这一点。

快速示例

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

您可以更改方法签名以返回您想要的类型。为简单起见,我使用 List<String>

关于json - ASP .Net MVC 5 JsonResult 缓存,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33402051/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com