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

  • A Bun-believable release that isn’t half-baked

    #​757 — October 17, 2025 Read on the Web JavaScript Weekly Bun 1.3: The Full-Stack JavaScript Runtime — Arriving a few hours after last week’s issue (natch!) Bun 1.3 remains the big news of the past week. Bun is a performance and DX-focused JavaScriptCore-powered runtime which, with v1.3, balances being a drop-in Node.js replacement with

    Posted by Posted on October 17, 2025
    0
  • Bringing Python apps into Node

    #​596 — October 14, 2025 Read on the Web 📂 A Modern Guide to Reading and Writing Files in Node — A comprehensive guide to various methods for working with files, from promise-based methods through to working with streams, processing files concurrently, using file handles, and memory-efficient techniques. Luciano Mammino A Way to Integrate Python ASGI with Node.js

    Posted by Posted on October 14, 2025
    0
  • Vite gets its own documentary

    #​756 — October 10, 2025 Read on the Web JavaScript Weekly ▶  Vite: The Documentary — From the same creators of the fantastic ▶️ Node.js, ▶️ Angular and ▶️ React documentaries comes an up to date look at Vite, the build tool that has taken the JavaScript ecosystem by storm in recent years. Many luminaries make an appearance to

    Posted by Posted on October 10, 2025
    0
  • npm security best practices to consider

    #​595 — October 7, 2025 Read on the Web 15 Recent Node Features That Can Replace Popular npm Packages — Many features that once required third-party packages are now built into the runtime itself. Here’s a look at some of the most notable that you may want to experiment with, prior to reducing unnecessary dependencies. Lizz

    Posted by Posted on October 7, 2025
    0
  • React 19.2 is in the building

    #​755 — October 3, 2025 Read on the Web JavaScript Weekly The State of JavaScript 2025 Survey — Each year, Devographics runs an epic survey of as many JavaScript community members as it can and turns the results into an interesting report on the state of the ecosystem – here’s the results from 2024. If

    Posted by Posted on October 3, 2025
    0
  • Using Node with Cloudflare Workers

    #​594 — September 30, 2025 Read on the Web 🗓️ We’re back after taking a week off for my birthday. I’ve never bothered to do that before, but I figured I’d give it a go, and.. it was good 😅 We’re now back every week until Christmas!__Peter Cooper, your editor A Year of Improving Node.js

    Posted by Posted on September 30, 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
  • A Bun-believable release that isn’t half-baked
  • Bringing Python apps into Node
  • Vite gets its own documentary
  • npm security best practices to consider
  • React 19.2 is in the building
https://flatlogic.com/generator
COPYRIGHT © 2025 - Codepolice