OutputCache returns invalid version with PostBack

感情迁移 提交于 2019-12-02 01:40:32

I think this is a bug in ASP .Net, and until its solved, here is a workaround.

For every postback I want a fresh version and not a cached version. But otherwise I want the cached version. So I can look if what kind of request this is. If this is a 'POST' I will get a new version, if this is a 'GET' I will get the version from cache. To do this, I setup a VaryByCustom cache setting on the usercontrol. And in my global.asax did this:

public override string GetVaryByCustomString(HttpContext context, string arg)
{
    if (arg.Trim().ToLower() == "getorpost")
    {
           //for a POST request (postback) force to return back a non cached output
            if (context.Request.RequestType.Equals("POST"))
            {
                return "post" + DateTime.Now.Ticks;
            }
            return "get";
     }
     return base.GetVaryByCustomString(context, arg);
}

From someone inside MS:

The output cache behavior for controls was originally written (and still is written) to key off of either the query-string collection or the form value collection. The internal logic determines which collection to look at based on whether the request is a GET or a POST. I agree that the behavior is less than obvious, but that was apparently the original intent of the control output caching behavior.

The two workarounds to include query string values are part of output cache decisions are:

  1. Mirror query-string values into hidden form variables if that is possible.
  2. Alternatively use the workaround you already discovered – which is to use VaryByCustom and GetVaryByCustomString. A custom implementation of GetVaryByCustomString can return a string containing one or more values read from Request.Querystring for POST requests to get the desired effect.

I agree with Garfield as to the cause, and think the suggestion to use VaryByCustom is a smart idea too. In order to do that, you can simply use Response.Cache.SetNoServerCaching() in Global.asax, which just requires sensing in Global.asax whether the page is a post-back or not. Here is a code example.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!