asp.net - Response.Flush 破坏页面缓存

标签 asp.net asp.net-mvc caching

我有一些代码用于用其他文本替换某些页面输出。我实现此目的的方法是将 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 的,因此不确定这如何转换到其他版本,但可能是相似的。 UpdateRequestCacheHttpApplication pipeline events 之一,并且它发生在 IHttpHandler(例如您的 Page 对象)完成处理请求之后。

所以...在页面内执行刷新看起来不太好。

关于asp.net - Response.Flush 破坏页面缓存,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2193628/

相关文章:

wcf - Microsoft.Data.Services.Client 是否缓存数据?

android - okio.Base64.encode ArrayIndexOutOfBoundsException 为什么会发生这种情况?

c# - jquery 无法从 C# var 获取变量值

asp.net - 根据方法名称过滤 log4net - 不太明白

asp.net-mvc - 在没有 IoC 容器的情况下如何对 Controller 进行单元测试?

asp.net-mvc - 为 ASP.Net MVC 设置测试的最佳实践是什么?使用/处理/等什么?

c# - 为什么我的 MVC5 Post Action 模型没有被填充

c# - 使用 WebMatrix 中的缓存是用户特定的还是应用程序特定的?

c# - 将集合发布到 ASP.NET WEB API

c# - 在 ASP.net 的浏览器中显示来自 Oracle 数据库的 PDF