asp.net – 最后修改标头在MVC

前端之家收集整理的这篇文章主要介绍了asp.net – 最后修改标头在MVC前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我最近遇到了最后修改标题

>如何和在哪里可以将其包括在MVC?
>包括它的优点是什么?

我想要一个示例如何最后修改标题可以包括在mvc项目,静态页面数据库查询以及?

它是不同于outputcache,如果是如何?

基本上,我想让浏览器自动清除缓存并显示最新的数据或页面,而不需要用户刷新或清除缓存。

解决方法

Last-Modified主要用于缓存。它被发送回资源​​,您可以跟踪修改时间。资源不一定是文件,而是任何东西。例如从具有UpdatedAt列的dB信息生成页面

它与If-Modified-Since头结合使用,每个浏览器在请求中发送(如果它先前已经接收到Last-Modified头)。

How and where can I include it in MVC?

Response.AddHeader

What are the advantages of including it?

对动态生成页面启用细粒度缓存(例如,您可以使用DB字段UpdatedAt作为最后修改的头)。

要使一切工作,你必须做这样的事情:

  1. public class YourController : Controller
  2. {
  3. public ActionResult MyPage(string id)
  4. {
  5. var entity = _db.Get(id);
  6. var headerValue = Request.Headers['If-Modified-Since'];
  7. if (headerValue != null)
  8. {
  9. var modifiedSince = DateTime.Parse(headerValue).ToLocalTime();
  10. if (modifiedSince >= entity.UpdatedAt)
  11. {
  12. return new HttpStatusCodeResult(304,"Page has not been modified");
  13. }
  14. }
  15.  
  16. // page has been changed.
  17. // generate a view ...
  18.  
  19. // .. and set last modified in the date format specified in the HTTP rfc.
  20. Response.AddHeader('Last-Modified',entity.UpdatedAt.ToUniversalTime().ToString("R"));
  21. }
  22. }

您可能需要在DateTime.Parse中指定格式。

参考文献:

> HTTP status codes
> HTTP headers

Disclamer:我不知道ASP.NET / MVC3是否支持你自己管理Last-Modified。

更新

您可以创建一个扩展方法

  1. public static class CacheExtensions
  2. {
  3. public static bool IsModified(this Controller controller,DateTime updatedAt)
  4. {
  5. var headerValue = controller.Request.Headers['If-Modified-Since'];
  6. if (headerValue != null)
  7. {
  8. var modifiedSince = DateTime.Parse(headerValue).ToLocalTime();
  9. if (modifiedSince >= updatedAt)
  10. {
  11. return false;
  12. }
  13. }
  14.  
  15. return true;
  16. }
  17.  
  18. public static ActionResult NotModified(this Controller controller)
  19. {
  20. return new HttpStatusCodeResult(304,"Page has not been modified");
  21. }
  22. }

然后使用它们像这样:

  1. public class YourController : Controller
  2. {
  3. public ActionResult MyPage(string id)
  4. {
  5. var entity = _db.Get(id);
  6. if (!this.IsModified(entity.UpdatedAt))
  7. return this.NotModified();
  8.  
  9. // page has been changed.
  10. // generate a view ...
  11.  
  12. // .. and set last modified in the date format specified in the HTTP rfc.
  13. Response.AddHeader('Last-Modified',entity.UpdatedAt.ToUniversalTime().ToString("R"));
  14. }
  15. }

猜你在找的asp.Net相关文章