SetLastModified is ignored when using OutputCacheAttribute

I have an ASP.NET MVC method (v3.0 on .NET 4.0) configured as follows:

[OutputCache(Duration = 31536000, Location = OutputCacheLocation.Any)] public virtual ActionResult Item() { this.Response.Cache.SetLastModified(new DateTime(2011, 01, 01)); return this.Content("hello world", "text/plain"); } 

I would expect this to return with the Last-Modified header set to Mon, 07 Feb 2011 00:00:00 GMT , as indicated, however it does return as the date the output was first cached in the output cache (i.e. .the first time the method was called because IIS was reset).

If I comment on the [OutputCache] attribute so that output caching is not completed, the Last-Modified header will return as expected, so it seems to be something in the output caching infrastructure that decided to ignore my specified value for this.

Any idea why this could be so? And is it possible to use its specified value as the Last-Modified date?

+4
source share
2 answers

Well, I never understood the reasons for this, but it seems like an error somewhere in the ASP.NET page caching infrastructure that the [OutputCache] attribute uses.

I ended up writing a custom [HttpCache] attribute with the same public interface, but which directly references the appropriate caching methods on the Response.Cache object, and not the delegation of the ASP.NET page caching infrastructure.

It works great. This is a shame that does not have a built-in attribute.

+2
source

During the controller's OnResultExecuting event, [OutputCache] creates an instance of System.Web.UI.Page to process the cache properties specified in the attribute. They do this because the page already has the logic to translate OutputCacheParameters into actual http cache directives.

https://aspnetwebstack.codeplex.com/SourceControl/latest#src/System.Web.Mvc/OutputCacheAttribute.cs

  public override void OnResultExecuting(ResultExecutingContext filterContext) { if (filterContext == null) { throw new ArgumentNullException("filterContext"); } if (!filterContext.IsChildAction) { // we need to call ProcessRequest() since there no other way to set the Page.Response intrinsic using (OutputCachedPage page = new OutputCachedPage(_cacheSettings)) { page.ProcessRequest(HttpContext.Current); } } } 

OutputCacheAttribute basically copies the output of the original handler (controller) to the page created to configure the cache.

The disadvantage here is that the headers added to the original HttpResponse are not copied to the new handler (Page). This means that it is not possible to set headers in response in the controller. The page that actually processes the request ignores these headers.

0
source

Source: https://habr.com/ru/post/1339031/


All Articles