Insights

Purge Cloudflare Cache Using C# Code

Learn how to clear the cache for Cloudflare in a C# console app

Introduction

Whenever you update a webpage, you should clear the cache for that URL so users can see the new information immediately. Here's how to do it in a C# console app so you don't have to login to Cloudflare each time.

Requirements

We need a couple of things before we can continue:

Zone ID and API Token

Head to the 'Overview' tab of your Cloudflare page, and look at the right column. There you should see your Zone ID. Copy that and save it for later.

zone-id-api-token

Next, click on Get your API token. On the following page, you will want to save the Global API Key.

global-api-key

NuGet

In Visual Studio, download the latest Newtonsoft.Json NuGet package.

Code for the cache purger

The following code purges specific URLs if they are listed, otherwise it will purge the entire site.

    
public class CloudflareCacheHelper
{
    private string _userEmail;
    private string _apiKey;
    private string _zoneId;

    // this is the Cloudflare Api
    private string _apiEndpoint = "https://api.cloudflare.com/client/v4";


    public CloudflareCacheHelper()
    {
        _zoneId = "";   //zone id you saved earlier
        _apiKey = "";   //global api key you saved earlier
        _userEmail = "[email protected]";
    }


    public bool Purge(List filePaths)
    {
        CloudflareResponse purgeResponse = null;

        byte[] data;

        // if there are a list of files to purge
        if (filePaths?.Count > 0)
        {
            
            // convert list of file URLs
            CloudflareFileInfo fileInfo = new CloudflareFileInfo
            {
                Files = filePaths
            };

            data = Encoding.ASCII.GetBytes(JsonConvert.SerializeObject(fileInfo));
        }
        else 
        {
            // purge the entire website 
            data = Encoding.ASCII.GetBytes(@"{""purge_everything"":true}");
        }

        // create the Http request
        HttpWebRequest purgeRequest = WebRequest.CreateHttp($"{_apiEndpoint}/zones/{_zoneId}/purge_cache");
        purgeRequest.Method = "POST";
        purgeRequest.ContentType = "application/json";
        purgeRequest.Headers.Add("X-Auth-Email", _userEmail);
        purgeRequest.Headers.Add("X-Auth-Key", _apiKey);
        purgeRequest.ContentLength = data.Length;

        // send the request
        using (Stream fileStream = purgeRequest.GetRequestStream())
        {
            fileStream.Write(data, 0, data.Length);
            fileStream.Flush();
        }

        // read the response
        using (WebResponse response = purgeRequest.GetResponse())
        {
            using (StreamReader purgeStream = new StreamReader(response.GetResponseStream()))
            {
                string responseJson = purgeStream.ReadToEnd();

                if (!string.IsNullOrEmpty(responseJson))
                    purgeResponse = JsonConvert.DeserializeObject(responseJson);
            }
        }
        return purgeResponse.Success;
    }
}
    

Classes for Json

These classes are to help serialize and deserialize the data and response.

Replace the () with <> for the list declarations.

    
public class CloudflareFileInfo
{
    [JsonProperty("files")]
    public List(string) Files { get; set; }
}


public class CloudflareResponse
{
    [JsonProperty("success")]
    public bool Success { get; set; }

    [JsonProperty("errors")]
    public IList(object) Errors { get; set; }

    [JsonProperty("messages")]
    public IList(object) Messages { get; set; }
}

    

Main function

Code that calls the Purge function.

Replace the () with <> for the list declarations.

    
static void Main(string[] args)
{
    CloudflareCacheHelper cch = new CloudflareCacheHelper();

    // purge select Urls
    bool purged = cch.Purge(new List(string) {
        "https://www.your-domain-here.com/your-newly-updated-page",
        "https://www.your-domain-here.com/your-newly-updated-page-2"
    });

    // purge entire site
    bool purgedEverything = cch.Purge(new List(string)());
}
    

Conclusion

Hope this code helps your Cloudflare purging needs!

We'll be cool about it. Promise.

Protect your website without compromising performance.

Improve your user experience and SEO with a faster and more available website.

Meet Gorman Law

Full Stack Developer

🏋️🎸🏈

Gorman is a Full Stack Developer and a University of Calgary alumni who has a background in Canada's financial industry. Outside of work, he likes to go rock climbing, try out new ice cream places, and watch sports.

Connect with Gorman