解决方法
Last-Modified主要用于缓存。它被发送回资源,您可以跟踪修改时间。资源不一定是文件,而是任何东西。例如从具有UpdatedAt列的dB信息生成的页面。
它与If-Modified-Since头结合使用,每个浏览器在请求中发送(如果它先前已经接收到Last-Modified头)。
How and where can I include it in MVC?
What are the advantages of including it?
对动态生成的页面启用细粒度缓存(例如,您可以使用DB字段UpdatedAt作为最后修改的头)。
例
要使一切工作,你必须做这样的事情:
- public class YourController : Controller
- {
- public ActionResult MyPage(string id)
- {
- var entity = _db.Get(id);
- var headerValue = Request.Headers['If-Modified-Since'];
- if (headerValue != null)
- {
- var modifiedSince = DateTime.Parse(headerValue).ToLocalTime();
- if (modifiedSince >= entity.UpdatedAt)
- {
- return new HttpStatusCodeResult(304,"Page has not been modified");
- }
- }
- // page has been changed.
- // generate a view ...
- // .. and set last modified in the date format specified in the HTTP rfc.
- Response.AddHeader('Last-Modified',entity.UpdatedAt.ToUniversalTime().ToString("R"));
- }
- }
您可能需要在DateTime.Parse中指定格式。
参考文献:
> HTTP status codes
> HTTP headers
Disclamer:我不知道ASP.NET / MVC3是否支持你自己管理Last-Modified。
更新
您可以创建一个扩展方法:
- public static class CacheExtensions
- {
- public static bool IsModified(this Controller controller,DateTime updatedAt)
- {
- var headerValue = controller.Request.Headers['If-Modified-Since'];
- if (headerValue != null)
- {
- var modifiedSince = DateTime.Parse(headerValue).ToLocalTime();
- if (modifiedSince >= updatedAt)
- {
- return false;
- }
- }
- return true;
- }
- public static ActionResult NotModified(this Controller controller)
- {
- return new HttpStatusCodeResult(304,"Page has not been modified");
- }
- }
然后使用它们像这样:
- public class YourController : Controller
- {
- public ActionResult MyPage(string id)
- {
- var entity = _db.Get(id);
- if (!this.IsModified(entity.UpdatedAt))
- return this.NotModified();
- // page has been changed.
- // generate a view ...
- // .. and set last modified in the date format specified in the HTTP rfc.
- Response.AddHeader('Last-Modified',entity.UpdatedAt.ToUniversalTime().ToString("R"));
- }
- }