带有 HTTP304 状态代码的 ASP.NET MVC2 浏览器缓存
在我工作的公司中,我们有一个使用 ASP.NET MVC2 开发并托管在 IIS7 上的 Web 应用程序。
在特定操作中,我们返回一个包含数组的 JsonResult 对象。该数组每天更新;因此,同一天发出的任何请求最终都会得到相同的响应。
public ActionResult SomeAction(int id)
{
// Some calculations
return Json(resultArray, JsonRequestBehavior.AllowGet);
}
由于操作成本较高,我们希望通过浏览器缓存等来提高性能。
我添加了一个缓存标头,因此我们告诉用户浏览器缓存结果,直到数据库的下一次更新。
除此之外,我想添加一个“Last-Modified”标头,这样浏览器就会询问源是否在指定日期之后被修改。
有什么方法可以实现这一点呢?我想检查数据库在浏览器询问的日期(Last-Modified header)之后是否被修改,如果没有修改,我想返回 304,就像 IIS 自动为静态文件(图像、css 和 js 文件等)所做的那样
In the company I work for, we have a web application developed with ASP.NET MVC2 and hosted on IIS7.
In a specific action, we return a JsonResult object holding an array. This array is updated daily; so any request coming in the same day will end up with the same response.
public ActionResult SomeAction(int id)
{
// Some calculations
return Json(resultArray, JsonRequestBehavior.AllowGet);
}
Since the operation is costly, we wanted to improve performance with browser caching and so.
I added a cache header, so we are telling user browser to cache the result till the next update of the database.
Besides that, I want to add a "Last-Modified" header, so browser will ask for if the source is modified after the specified date.
What is the way to accomplish that? I want to check if DB is modified after the date browser asked (Last-Modified header) and if not modified, I want to return 304 just IIS automatically does for static files (images, css and js files etc)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
添加真实的
Last-Modified
标头。如果你的数据每天更新,你应该知道什么时候更新,对吧?然后,在操作方法的开头,通过解析 HTTP 请求中的日期时间字符串并检查数据的实际上次修改时间,添加对传入
If-Modified-Since
的检查。如果数据尚未修改,只需 手动返回304。如果有,请执行操作方法通常执行的操作。您还可以(或者相反)在您的内容中返回 ETag ,其值必须每当内容改变时就改变。
然后将整个内容包装为 ASP.NET MVC Action Filter 为了可重用性。
然后 在您的博客上发布相关内容。 :)
为了防止客户端行为不当以及不缓存任何内容的客户端(可能您的数据是由应用程序而不是桌面浏览器加载的),您可以将操作方法的结果存储在 ASP.NET 输出中无论如何都要缓存,以避免昂贵的操作。您可能必须
VaryByCustom
来实现绝对过期。
Add a truthful
Last-Modified
header. If your data is updated daily, you should know when, right?Then, in the beginning of the action method, add a check for the incoming
If-Modified-Since
by parsing that datetime string in the HTTP request and checking against the actual last-modified time of your data. If the data hasn't been modified, just return 304 manually. If it has, do what the action method normally does.You could also (or instead) return an ETag with your content, the value of which must then change whenever the content changes.
Then wrap the whole thing up as an ASP.NET MVC Action Filter for reusability.
Then post about it on your blog. :)
To protect against misbehaving clients and clients who don't cache anything (perhaps your data is loaded by an application and not a desktop browser), you could store the result of the action method in the ASP.NET output cache anyway, to avoid the costly operation. You'd probably have to
VaryByCustom
to implement absolute expiration though.