我有一些代码用于用其他文本替换某些页面输出。我实现此目的的方法是将 Response.Filter 设置为流,刷新响应,然后将该流读回到字符串中。从那里我可以操作字符串并输出结果代码。您可以在 Render a view as a string 中查看基本代码。 .
但是,我注意到第一次 Response.Flush 调用后页面缓存不再起作用。
我整理了一个简单的 ASP.NET WebApp 作为示例。我有一个 Default.aspx,其中 @OutputCache 设置为 30 秒。这一切所做的就是输出 DateTime.Now.ToLongTimeString()。我覆盖渲染。如果我执行 Response.Flush (即使在 base.Render 之后),页面也不会被缓存。这与我设置的任何编程可缓存性无关。
看来 Response.Flush 完全破坏了正在使用的任何页面缓存。这是为什么?
额外加分:有没有一种方法可以完成我想要的任务(将输出渲染为字符串),并且不会导致页面缓存被绕过?
ASPX 页面:
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="TestCacheVsFlush._Default" %>
<%@ OutputCache Duration="30" VaryByParam="none" %>
<%= DateTime.Now.ToLongTimeString() %>
代码隐藏(页面已缓存):
protected override void Render(HtmlTextWriter writer)
{
base.Render(writer);
}
代码隐藏(页面未缓存):
protected override void Render(HtmlTextWriter writer)
{
base.Render(writer);
Response.Flush();
}
代码隐藏(页面仍未缓存):
protected override void Render(HtmlTextWriter writer)
{
base.Render(writer);
Response.Cache.SetCacheability(HttpCacheability.Server);
Response.Cache.SetExpires(DateTime.Now.AddSeconds(30));
Response.Flush();
}
最佳答案
好的,我想我已经为您提供了部分答案。
来自here :
Output cache module populates the IHttpCachePolicy intrinsic in BeginRequest stage if a matching profile is found. Other modules can still change cache policy for the current request which might change user-mode or kernel mode caching behavior. Output cache caches 200 responses to GET requests only. If some module already flushed the response by the time request reaches UpdateRequestCache stage or if headers are suppressed, response is not cached in output cache module.
那篇文章是特定于 IIS7 的,因此不确定这如何转换到其他版本,但可能是相似的。 UpdateRequestCache
是 HttpApplication pipeline events 之一,并且它发生在 IHttpHandler(例如您的 Page 对象)完成处理请求之后。
所以...在页面内执行刷新看起来不太好。
关于asp.net - Response.Flush 破坏页面缓存,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2193628/