A bug in ASP. NET 2.0 is that the max-age header cannot be changed. When max-age is set to 0, ASP. NET 2.0 sets Cache-control to private, because max-age = 0 means no Cache is required. Therefore, there is no way to make ASP. NET 2.0 return the cache response header. This is because the ASP. net ajax framework intercepts Web service calls and sets max-age to 0 as the default value before executing a request.
- public string CachedGet2()
- {
- TimeSpan cacheDuration = TimeSpan.FromMinutes(1);
- FieldInfo maxAge = Context.Response.Cache.GetType().GetField("_maxAge",
- BindingFlags.Instance|BindingFlags.NonPublic);
- maxAge.SetValue(Context.Response.Cache, cacheDuration);
- Context.Response.Cache.SetCacheability(HttpCacheability.Public);
- Context.Response.Cache.SetExpires(DateTime.Now.Add(cacheDuration));
- Context.Response.Cache.AppendCacheExtension(
- "must-revalidate, proxy-revalidate");
- return DateTime.Now.ToString();
- }
Now max-age is set to 60, so the browser will cache the response for 60 seconds. If you make the same call again within 60 seconds, the same response will be returned. The test output here shows the time returned from the server:
One minute later, when the cache expires, the browser sends a request to the server again. The client code is as follows:
- function testCache()
- {
- TestService.CachedGet(function(result)
- {
- debug.trace(result);
- });
- }
Another problem is solved. In the web. config file, you will see that ASP. NET Ajax has added the following node values:
- <system.web>
- <trust level="Medium"/>
This prevents us from setting the _ maxAge field of the Response object because it requires reflection. Therefore, you have to delete this level of trust or place it as Full.
- <system.web>
- <trust level="Full"/>
- Analysis of configuration files in ASP. NET
- . Net ria Services is as convenient as ASP. NET
- Overview of the UpdatePanel control in ASP. net ajax Extensions
- ASP. NET calls the UpdatePanel Update () method
- Introduction to the ASP. net ajax wcf Service