Skip to content

Codepolice

  • ⤫

Signing a request to set up a custom Amazon CloudFront Distribution with C#

Posted by Judy Alvarez Posted on February 28, 2022March 1, 2022
0

I love most of Amazon’s Web Services (AWS). CloudFront is their CDN service and they have an awesome feature that lets you host your files on your server and then Amazon automatically grabs the files from your server and puts them on their CDN. This makes it possible to easily modify your files without having to download them from some S3 bucket or something to make changes.

Unfortunately, Amazon doesn’t provide a UI to set up a “Custom Distribution” so you have to do a post request to a URL and send them some XML. It’s maybe not that hard but I think they could provide us with some simple page where you just paste some XML and sent the request. But you have to do it yourself. The only thing I had issues with was signing the request and getting your “encrypted” secret.

I found some code on Stack Overflow (as usual) and just made some small modifications to it for doing a Cloud Front setup request.

public static void InvalidateContent() {
    string httpDate = Helper.GetHttpDate();

    string AWSSecret = "YOUR SECRET";
    string AWSAccessKeyId = "YOUR ACCESS KEY";

    ASCIIEncoding encoding = new ASCIIEncoding();
    string postData = @"<DistributionConfig xmlns='http://cloudfront.amazonaws.com/doc/2010-11-01/'>
        <CustomOrigin>
            <DNSName>dist.alternativeto.net</DNSName>
            <HTTPPort>80</HTTPPort>
            <HTTPSPort>443</HTTPSPort>
            <OriginProtocolPolicy>match-viewer</OriginProtocolPolicy>
        </CustomOrigin>
        <CallerReference>" + httpDate + @"</CallerReference>
        <CNAME>static.alternativeto.net</CNAME>
        <Comment>My comments</Comment>
        <Enabled>true</Enabled>
        <Logging>
            <Bucket>mylogs.s3.amazonaws.com</Bucket>
            <Prefix>myprefix/</Prefix>
        </Logging>
    </DistributionConfig>";
    byte[] data = encoding.GetBytes(postData);

    // Prepare web request...
    HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create("https://cloudfront.amazonaws.com/2010-11-01/distribution");
    webRequest.Method = "POST";
    webRequest.ContentType = "text/xml";
    webRequest.Headers.Add("x-amz-date", httpDate);

    Encoding ae = new UTF8Encoding();
    HMACSHA1 signature = new HMACSHA1(ae.GetBytes(AWSSecret.ToCharArray()));

    string b64 = Convert.ToBase64String(signature.ComputeHash(ae.GetBytes(webRequest.Headers["x-amz-date"].ToCharArray())));

    webRequest.Headers.Add(HttpRequestHeader.Authorization, "AWS" + " " + AWSAccessKeyId + ":" + b64);

    webRequest.ContentLength = data.Length;

    Stream newStream = webRequest.GetRequestStream();
    // Send the data.
    newStream.Write(data, 0, data.Length);
    newStream.Close();
}

/// <summary>
/// Gets a proper HTTP date
/// </summary>
public static string GetHttpDate() {
    // Setting the Culture will ensure we get a proper HTTP Date.
    string date = System.DateTime.UtcNow.ToString("ddd, dd MMM yyyy HH:mm:ss ", System.Globalization.CultureInfo.InvariantCulture) + "GMT";
    return date;
}
Categories: JavascriptTagged: asp .net ajax, asp net blogs, asp net boiler plate, asp net core cms, asp net core interview questions and answers for experienced, asp net core pdf viewer, asp net core web development, asp net crud, asp net environment variables, asp net in hindi, asp net msdn, asp net mvc generate pdf from view, asp net mvc interview questions and answers pdf, asp net pdf component, asp net pdf editor, asp net read excel file, asp net server, asp net table, asp net web pages, building microservices using asp net core 5.0 and docker, cheap asp net hosting, control state in asp net, convert pdf to html asp net, interview questions on asp net for experienced, jquery asp net, kudvenkat asp net core, passport authentication in asp net, shopping cart in asp net c# source code, textarea in asp net, validation for email in asp net

Post navigation

Previous Previous post: Use your IIS logs with WCAT
Next Next post: Debug and fix the z-index bug in IE6 and IE7

Related Posts

  • What’s the story? JavaScript’s 30!

    #​764 — December 5, 2025 Read on the Web JavaScript Weekly 🎉  JavaScript Turns 30 Years Old  🎉 Back in May 1995, a 33 year old Brendan Eich built the first prototype of JavaScript in just ten days, originally codenamed Mocha (and then LiveScript). On December 4, 1995, Netscape and Sun Microsystems officially announced ‘JavaScript’ in a

    Posted by Posted on December 5, 2025
    0
  • Comparing performance across Node versions and ARM vs x86

    #​603 — December 2, 2025 Read on the Web Tinybench 6.0: A Tiny, Simple Benchmarking Library — Uses whatever precise timing capabilities are available (e.g. process.hrtime or performance.now). You can then benchmark whatever functions you want, specify how long or how many times to benchmark for, and get a variety of stats in return –

    Posted by Posted on December 2, 2025
    0
  • Algorithms visualized and demonstrated in JavaScript

    #​763 — November 28, 2025 Read on the Web JavaScript Weekly Over 150 Algorithms and Data Structures Demonstrated in JS — Examples of many common algorithms (e.g. bit manipulation, Pascal’s triangle, Hamming distance) and data structures (e.g. linked lists, tries, graphs) with explanations. Available in eighteen other written languages too. Oleksii Trekhleb et al. TypeScript: From

    Posted by Posted on November 28, 2025
    0
  • Guess who’s back, back again? Shai-Hulud.

    #​602 — November 25, 2025 Read on the Web How a Summer in Abruzzo Helped Bring Type Stripping to Node.js — Node.js TSC member and committer Marco tells the personal tale of what it took to bring type stripping (now considered stable) to Node. It’s neat to get the back story. He’s now working on

    Posted by Posted on November 25, 2025
    0
  • A significant Angular release

    #​762 — November 21, 2025 Read on the Web JavaScript Weekly Google Announces Angular v21 — The Google team has gone all out with this significant release of its popular JavaScript framework. They’ve put together a retro game-themed adventure-based tour of what’s new, along with top notch videos showing off features like its new signal-based

    Posted by Posted on November 21, 2025
    0
  • Did you know Node has a ‘deprecate’ method?

    #​601 — November 18, 2025 Read on the Web Node.js v25.2.1 (Current) Released (and 25.2.0 with Type Stripping Marked ‘Stable’) — v25.2.0 was released hours after we hit send last week (often the way!) and marked type stripping as stable, meaning all major server-side runtimes now support TypeScript officially (at least in type-stripping form). v25.2.1,

    Posted by Posted on November 18, 2025
    0
Judy Alvarez

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

Codepolice

  • Github
  • Atlassian
  • Flatlogic
  • Xero
  • Jetbrains
  • Figma
  • What’s the story? JavaScript’s 30!
  • Comparing performance across Node versions and ARM vs x86
  • Algorithms visualized and demonstrated in JavaScript
  • Guess who’s back, back again? Shai-Hulud.
  • A significant Angular release
https://flatlogic.com/generator
COPYRIGHT © 2025 - Codepolice