Does anyone know why if is have cookies on my page, the output cache does not work !
Example page
<%@ Page Language="VB" AutoEventWireup="false" CodeFile="ct.aspx.vb" Inherits="ct" %>
<%@ OutputCache Duration="600" Location="Server" VaryByParam="none" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<h1>Cache test</h1>
<p id="rndout" runat="server"></p>
</div>
</form>
</body>
</html>
Example code behind:
Partial Class ct
Inherits System.Web.UI.Page
Protected Sub Page_Load(sender As Object, e As System.EventArgs) Handles Me.Load
Dim rc As New Random()
Dim rn As Integer
rn = rc.Next()
rndout.InnerHtml = rn.ToString
Response.Cookies("sym")("hello") = "world"
Response.Cookies("sym").Expires = DateTime.Now.AddDays(370)
Response.Cookies("sym").Domain = Application.Get("cookieurl")
End Sub
End Class
when deployed to iis 6 or 7 this does not cache, however if i comment out the 3 Response.Cookies lines it does.
When run up in VS it works fine both ways.
Is there some setting in iis/web.config etc to allow outputcache while i set response.cookies. I understand the cookie content will be cached as well as it is just a part of the http response that is cached.
Best Answer
After doing a fair bit of research into this problem, I came to understand and work-around the problem.
The reason output cache doesn't play nice with cookies
So the reason the output cache will not cache a response with cookies is that a cookie could be user-specific (e.g. authentication, analytical tracking, etc.). If one or more cookies with the property
HttpCookie.Shareable = false
, then the output cache considers the response uncacheable.Including cookies with a cached response
This is where it get's tricky. The output cache caches the response headers and content together and doesn't provide any hooks to modify these before sending them back to the user. However, I wrote the following custom output cache provider to provide the ability to modify a cached response's headers before they are sent back to the user (requires the Fasterflect nuget package):
You would wire it up like this:
And could use it like this to insert cookies: