ASP.NET MVC2 Browser caching with HTTP304 Status Code
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 开发者_JS百科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)
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.
精彩评论