Purge Cloudflare Cache Using C# Code

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

July 24, 2022

By Gorman Law

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;
<span class="hljs-comment">// this is the Cloudflare Api</span>
<span class="hljs-keyword">private</span> <span class="hljs-keyword">string</span> _apiEndpoint = <span class="hljs-string">"https://api.cloudflare.com/client/v4"</span>;


<span class="hljs-function"><span class="hljs-keyword"><span class="hljs-function"><span class="hljs-keyword">public</span></span></span><span class="hljs-function"> </span><span class="hljs-title"><span class="hljs-function"><span class="hljs-title">CloudflareCacheHelper</span></span></span><span class="hljs-function">(</span><span class="hljs-params"></span><span class="hljs-function"><span class="hljs-params"></span>)</span></span>
{
    _zoneId = <span class="hljs-string">""</span>;   <span class="hljs-comment">//zone id you saved earlier</span>
    _apiKey = <span class="hljs-string">""</span>;   <span class="hljs-comment">//global api key you saved earlier</span>
    _userEmail = <span class="hljs-string">"[email protected]"</span>;
}


<span class="hljs-function"><span class="hljs-keyword"><span class="hljs-function"><span class="hljs-keyword">public</span></span></span><span class="hljs-function"> </span><span class="hljs-keyword"><span class="hljs-function"><span class="hljs-keyword">bool</span></span></span><span class="hljs-function"> </span><span class="hljs-title"><span class="hljs-function"><span class="hljs-title">Purge</span></span></span><span class="hljs-function">(</span><span class="hljs-params"><span class="hljs-function"><span class="hljs-params">List</span></span></span></span><string><span class="hljs-function"><span class="hljs-params"><span class="hljs-function"><span class="hljs-params"> filePaths</span></span></span><span class="hljs-function">)</span></span>
{
    CloudflareResponse purgeResponse = <span class="hljs-literal">null</span>;

    <span class="hljs-keyword">byte</span>[] data;

    <span class="hljs-comment">// if there are a list of files to purge</span>
    <span class="hljs-keyword">if</span> (filePaths?.Count &gt; <span class="hljs-number">0</span>)
    {
        
        <span class="hljs-comment">// convert list of file URLs</span>
        CloudflareFileInfo fileInfo = <span class="hljs-keyword">new</span> CloudflareFileInfo
        {
            Files = filePaths
        };

        data = Encoding.ASCII.GetBytes(JsonConvert.SerializeObject(fileInfo));
    }
    <span class="hljs-keyword">else</span> 
    {
        <span class="hljs-comment">// purge the entire website </span>
        data = Encoding.ASCII.GetBytes(<span class="hljs-string">@"{""purge_everything"":true}"</span>);
    }

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

    <span class="hljs-comment">// send the request</span>
    <span class="hljs-keyword">using</span> (Stream fileStream = purgeRequest.GetRequestStream())
    {
        fileStream.Write(data, <span class="hljs-number">0</span>, data.Length);
        fileStream.Flush();
    }

    <span class="hljs-comment">// read the response</span>
    <span class="hljs-keyword">using</span> (WebResponse response = purgeRequest.GetResponse())
    {
        <span class="hljs-keyword">using</span> (StreamReader purgeStream = <span class="hljs-keyword">new</span> StreamReader(response.GetResponseStream()))
        {
            <span class="hljs-keyword">string</span> responseJson = purgeStream.ReadToEnd();

            <span class="hljs-keyword">if</span> (!<span class="hljs-keyword">string</span>.IsNullOrEmpty(responseJson))
                purgeResponse = JsonConvert.DeserializeObject<cloudflareresponse>(responseJson);
        }
    }
    <span class="hljs-keyword">return</span> 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; }

[<span class="hljs-meta"><span class="hljs-meta">JsonProperty(</span><span class="hljs-meta-string"><span class="hljs-meta"><span class="hljs-meta-string">"errors"</span></span></span><span class="hljs-meta">)</span></span>]
<span class="hljs-function"><span class="hljs-keyword"><span class="hljs-function"><span class="hljs-keyword">public</span></span></span><span class="hljs-function"> </span><span class="hljs-title"><span class="hljs-function"><span class="hljs-title">IList</span></span></span><span class="hljs-function">(</span><span class="hljs-params"><span class="hljs-keyword"><span class="hljs-function"><span class="hljs-params"><span class="hljs-keyword">object</span></span></span></span></span><span class="hljs-function">) Errors</span></span> { <span class="hljs-keyword">get</span>; <span class="hljs-keyword">set</span>; }

[<span class="hljs-meta"><span class="hljs-meta">JsonProperty(</span><span class="hljs-meta-string"><span class="hljs-meta"><span class="hljs-meta-string">"messages"</span></span></span><span class="hljs-meta">)</span></span>]
<span class="hljs-function"><span class="hljs-keyword"><span class="hljs-function"><span class="hljs-keyword">public</span></span></span><span class="hljs-function"> </span><span class="hljs-title"><span class="hljs-function"><span class="hljs-title">IList</span></span></span><span class="hljs-function">(</span><span class="hljs-params"><span class="hljs-keyword"><span class="hljs-function"><span class="hljs-params"><span class="hljs-keyword">object</span></span></span></span></span><span class="hljs-function">) Messages</span></span> { <span class="hljs-keyword">get</span>; <span class="hljs-keyword">set</span>; }

}

</code>

Main function

Code that calls the Purge function.

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

    
static void Main(string[] args)
{
    CloudflareCacheHelper cch = new CloudflareCacheHelper();
<span class="hljs-comment">// purge select Urls</span>
<span class="hljs-keyword">bool</span> purged = cch.Purge(<span class="hljs-keyword">new</span> List(<span class="hljs-built_in">string</span>) {
    <span class="hljs-string">"https://www.your-domain-here.com/your-newly-updated-page"</span>,
    <span class="hljs-string">"https://www.your-domain-here.com/your-newly-updated-page-2"</span>
});

<span class="hljs-comment">// purge entire site</span>
<span class="hljs-keyword">bool</span> purgedEverything = cch.Purge(<span class="hljs-keyword">new</span> List(<span class="hljs-built_in">string</span>)());

}

Conclusion

Hope this code helps your Cloudflare purging needs!

Gorman Headshot

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.

Second CTA Ogilvy's Legacy

Today, David Ogilvy's influence can still be felt in the world of advertising.

Ogilvy's Influence Example
Emphasis on research Market research is a crucial part of any successful advertising campaign
Focus on headlines A strong headline can make the difference between an ad that is noticed and one that is ignored
Use of visuals Compelling images and graphics are essential for capturing audience attention