gpt4 book ai didi

asp.net - MVC 中最后修改的 header

转载 作者:行者123 更新时间:2023-12-03 07:23:50 25 4
gpt4 key购买 nike

我最近遇到了“Last-Modified” header 。

  • 如何以及在何处将其包含在 MVC 中?
  • 加入它有什么好处?

我想要一个示例,如何将最后修改的 header 包含在 mvc 项目中,以及静态页面和数据库查询?

它与outputcache有什么不同吗?如果有的话,又是怎样的?

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

最佳答案

Last-Modified主要用于缓存。它将发回您可以跟踪修改时间的资源。资源不一定是文件,而是任何东西。例如,根据 dB 信息生成的页面,其中包含 UpdatedAt 列。

它与每个浏览器在请求中发送的 If-Modified-Since header 结合使用(如果它之前已收到 Last-Modified header )。

How and where can I include it in MVC?

Response.AddHeader

What are the advantages of including it?

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

示例

要使一切正常工作,您必须执行以下操作:

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 中指定格式。

引用文献:

免责声明:我不知道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"));
}
}

关于asp.net - MVC 中最后修改的 header ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10498135/

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