Thursday, November 6, 2014

HttpClient Caching

Is any one of you have an experience on when send http request through http client the response become the same (no change) even your source of the response (server) is updated.

It is the way that default http protocol behaves

By default HttpClient use a cache to store responses that come up with response headers without Cache-Control header. ( Ref: HTTP Header fields)

In a scenario you need to change the cache behavior with HttpClient you can have two options

1. Edit the service (server) to response with relevant cache headers
2. Modify your request headers

Edit the service (server) to response with relevant cache headers

In this model it give two benefits to you
  • A content you will not use again is not stored in the client machine.
  • Other requests can benefit from the cache (when using the same instance of HttpClient).
In your web service go to web.config file and in-side the system.serviceModel add following tag with relevant headers you need


     <client>
      <endpoint address="http://localhost/..." >
        <headers>
          <Cache-Control>no-cache</Cache-Control>
        </headers>
      </endpoint>
    </client>


Modify your request headers

if you don't have the access to the server you can go with this option. Just ad additional header with HttpClient and send the request then response automatically include these headers

HttpClient Client = new HttpClient();
Client.DefaultRequestHeaders.Add("Cache-Control""no-cache");


Now your HttpClient is ready to handle http request with no cache .


here is Cache contol values that provide from W3 with Http headers.

    cache-directive = cache-request-directive
         | cache-response-directive
    cache-request-directive =
           "no-cache"                          
         | "no-store"                          
         | "max-age" "=" delta-seconds         
         | "max-stale" [ "=" delta-seconds ]   
         | "min-fresh" "=" delta-seconds       
         | "no-transform"                      
         | "only-if-cached"                    
         | cache-extension                     
     cache-response-directive =
           "public"                               
         | "private" [ "=" <"> 1#field-name <"> ] 
         | "no-cache" [ "=" <"> 1#field-name <"> ]
         | "no-store"                             
         | "no-transform"                         
         | "must-revalidate"                      
         | "proxy-revalidate"                     
         | "max-age" "=" delta-seconds            
         | "s-maxage" "=" delta-seconds           
         | cache-extension 
 
 
 
 Enjoy the code .. 
 
 




0 comments: