public bool PurgeCache(string zoneIdentifier, IEnumerable<string> urls, bool purgeEverything = false, bool throwExceptionOnError = false)
{
try
{
if (String.IsNullOrEmpty(zoneIdentifier)) throw new ArgumentNullException("zoneIdentifier");
if ((urls == null || !urls.Any()) && !purgeEverything)
{
//Its probably worthy to log that we were going to purge pages but no url was given
Log.Info("PurgeIndividualPages was called but there were no urls given to purge nor are we purging everything");
return true;
}
using (var client = new HttpClient())
{
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
string json;
if (purgeEverything)
{
json = "{\"purge_everything\":true}";
}
else
{
json = String.Format("{{\"files\":{0}}}", JsonConvert.SerializeObject(urls));
}
HttpRequestMessage request = new HttpRequestMessage()
{
RequestUri = new Uri(CLOUDFLARE_API_BASE_URL + "zones/" + zoneIdentifier + "/purge_cache"),
Method = HttpMethod.Delete,
Content = new StringContent(json, Encoding.UTF8, "application/json")
};
//Add in the ApiKey and AccountEmail
AddRequestHeaders(request);
var responseContent = client.SendAsync(request).Result.Content;
var stringVersion = responseContent.ReadAsStringAsync().Result;
try
{
BasicCloudflareResponse response = responseContent.ReadAsAsync<BasicCloudflareResponse>().Result;
if (!response.Success)
{
//Something went wrong log the response
Log.Error(String.Format("Something went wrong because of {1}", response.Messages.ToString()));
return false;
}
}
catch(Exception e)
{
Log.Error(String.Format("Something went wrong getting the purge cache response back. The url that was used is {0}. The json that was used is {1}. The raw string value is {1}", request.RequestUri.ToString(), json, stringVersion));
return false;
}
return true;
}
}
catch (Exception e)
{
Log.Error(String.Format("Failed to purge individual pages for urls {0}", urls.Select(x => {return x + "x";})), e);
if(throwExceptionOnError)
{
throw e;
}
else
{
return false;
}
}
}