Deploy .NET 8 Native AOT Functions to Cloudflare Workers – Step‑by‑Step Guide

Mahmut Sarıkaya 5 dk okuma 4 Görüntülenme 0
Deploy .NET 8 Native AOT Functions to Cloudflare Workers – Step‑by‑Step Guide

Why Edge Computing Needs Native AOT

Edge platforms such as Cloudflare Workers promise sub‑millisecond latency because code runs inside the network’s closest data centre. However, the standard .NET runtime carries a 30‑40 MB footprint that exceeds the 10 MB script limit imposed by Workers. .NET 8 Native AOT compiles IL directly to native machine code and can emit WebAssembly, shrinking the binary to under 5 MB while retaining the productivity of C#. This shift enables developers to bring existing .NET libraries to the edge without rewriting them in JavaScript.

System Requirements

Before you start, verify the following on your development machine:

  • Operating system: macOS 12+, Windows 10 1809+, or a recent Linux distribution.
  • .NET 8 SDK (version 8.0.100 or later).
  • Node.js 18+ (required by Cloudflare’s Wrangler CLI).
  • Cloudflare account with a Workers namespace ready for deployment.

All components are free and can be installed with a single command line.

Install the Toolchain

dotnet --list-sdks && echo "Installing .NET 8 SDK" && brew install dotnet@8 && npm install -g wrangler

The command prints the currently installed SDKs, installs .NET 8 via Homebrew on macOS (use the appropriate package manager on Windows or Linux), and globally adds Wrangler, the official CLI for Cloudflare Workers.

Create a .NET 8 Native AOT Project

Generate a minimal console project that will be transformed into a WebAssembly module:

dotnet new console -n EdgeFunction -f net8.0

Navigate into the folder and add the AOT package reference:

cd EdgeFunction && dotnet add package Microsoft.NET.Runtime.Aot && dotnet add package Microsoft.NET.Sdk.WebAssembly

These packages enable the AOT compiler and the WebAssembly SDK extensions required for the next step.

Write the C# Handler

Replace the autogenerated Program.cs with a small, stateless function that Cloudflare Workers can invoke. The function must be public, static, and return a serializable type.

using System; <br/> public class Function <br/> { <br/>     public static string Handle(string name) => $\"Hello, {name}!\"; <br/> }

This example echoes a greeting; real‑world code could call a database, perform JWT validation, or render a template.

Configure WebAssembly Output

Edit the project file (EdgeFunction.csproj) to enable AOT and target the browser‑wasm runtime. Insert the following PropertyGroup:

<PropertyGroup> <br/>   <TargetFramework>net8.0</TargetFramework> <br/>   <RuntimeIdentifier>browser-wasm</RuntimeIdentifier> <br/>   <PublishAOT>true</PublishAOT> <br/>   <SelfContained>true</SelfContained> <br/>   <InvariantGlobalization>true</InvariantGlobalization> <br/> </PropertyGroup>

The PublishAOT flag tells the compiler to produce native code, while InvariantGlobalization removes unnecessary locale data, keeping the final Wasm module under the 5 MB ceiling.

Build the WebAssembly Binary

Run the publish command with the Release configuration. The output will be placed in bin/Release/net8.0/browser-wasm/publish/.

dotnet publish -c Release -r browser-wasm --self-contained false

After the build finishes, you will find a dotnet.wasm file and a small runtime.js bootstrap script. These two assets are the only files you need to upload to Cloudflare.

Prepare the Worker Project

Initialize a Workers project with Wrangler:

wrangler init edge-dotnet --type=javascript

Replace the generated index.js with a thin wrapper that loads the WebAssembly module and forwards the request to the C# handler.

addEventListener('fetch', event => { <br/>  event.respondWith(handleRequest(event.request)); <br/>}); <br/> async function handleRequest(request) { <br/>  const wasm = await fetch('dotnet.wasm'); <br/>  const { instance } = await WebAssembly.instantiateStreaming(wasm); <br/>  const { Handle } = instance.exports; <br/>  const url = new URL(request.url); <br/>  const name = url.searchParams.get('name') || 'World'; <br/>  const resultPtr = Handle(name); <br/>  // Assume a helper that reads a null‑terminated string from memory <br/>  const result = readString(instance.exports.memory, resultPtr); <br/>  return new Response(result, {status:200}); <br/>}

The wrapper demonstrates how to call the exported Handle function, pass a simple string argument, and return the result as an HTTP response. In production you would add error handling, CORS headers, and possibly a JSON serializer.

Deploy to Cloudflare

Copy dotnet.wasm and runtime.js into the Worker’s public/ folder, then run the publish command:

wrangler publish

Wrangler uploads the script, the Wasm binary, and the bootstrap file to the edge. The deployment usually completes in under 30 seconds, and the new Worker becomes reachable at the URL assigned by Cloudflare (e.g., https://edge-dotnet.yourdomain.workers.dev).

Test and Debug

A quick curl request proves the function works:

curl "https://edge-dotnet.yourdomain.workers.dev?name=Alice"

The response should be Hello, Alice!. If you see a 500 error, check the Workers log with wrangler tail, which streams real‑time console output from the edge. Common pitfalls include mismatched string encoding between JavaScript and the Wasm memory buffer, or forgetting to set InvariantGlobalization which can cause the binary to exceed the size limit.

Conclusion

Deploying .NET 8 Native AOT functions to Cloudflare Workers bridges the gap between enterprise‑grade C# code and ultra‑low‑latency edge execution. By compiling to WebAssembly, you keep the runtime size under the platform’s strict limits, while still leveraging the full power of the .NET ecosystem. The step‑by‑step workflow—install SDK, create an AOT project, publish as Wasm, wrap with a tiny JavaScript shim, and push with Wrangler—fits into existing CI/CD pipelines and can be automated with GitHub Actions or Azure DevOps.

Sources

  • Microsoft .NET 8 Native AOT documentation
  • Cloudflare Workers official documentation
  • WebAssembly.org – Getting Started with Wasm

Author: Mahmut Sarıkaya — sarikayadev.com

Etiketler: #.NET 8 #Native AOT #Cloudflare Workers #WebAssembly #edge computing
Paylaş:
M

Yazar

Mahmut Sarıkaya

yazılım Geliştirici

Yorumlar

Henüz yorum yok. İlk yorumu siz yapın!

Yorum Bırakın

2 + 3 =