Your first serverless .NET function with OpenFaaS

After reading Alex Ellis’ blog post about creating serverless Python functions using his OpenFaaS framework, I was curious what it would look like to create one using .NET and C#. My main objective was to port my Azure Functions over to Docker containers to help with Docker adoption at my organization (plus help me out with my CI/CD pipelines). We’re using some Azure Functions at work that use Node and C# so my motivation is quite high to try to port those over!

I had spent some time playing around with making some simple Python functions and loved the experience. Create one handler.py and requirements.txt file and you're off to the races!

Step 0 If you view the blog post I mention above you can get FaaS and the CLI installed and configured and also get some sample functions working. We’re going to skip to Step 3 but use .NET Core instead of Python.

Step 1 — Write your function

First, create the directory to hold your function:

$ mkdir -p ~/functions/hello-csharp$ cd ~/functions/hello-csharp

Now create two files: a Function.csproj and a FunctionHandler.cs. You can also clone the FaaS repo from GitHub and copy these two files from the template folder. Here's a link.

Just like Alex’s post, all your functions should be specified in a YAML file. The YAML file tells the FaaS CLI what to build and deploy onto your OpenFaaS cluster.

If you’re familiar with .NET Core (since the change from dnx) you know you can add NuGet packages to your csproj file and have them pulled down during build. Let’s add Newtonsoft.Json so we can work with JSON in our function.

We’re using Newtonsoft to parse the input sent to the function, and if a value property is present in the payload we cast that to an int and use that as the value to calculate factors of the number (otherwise we just default it to the current year).

The function isn’t super robust in that if you provide a non-JSON format it errors out, so I’ll leave that exercise to you.

Step 3 — Rejoice (and copy all of your Azure Functions to FaaS) This is basically a direct-from-Azure-Functions port of something I wrote in Azure a bit ago. I’ve also written a “Guid.Empty” function as well as Base64 encode and decode functions, all using C# (and then porting them to FaaS).

Feel free to message me on Twitter (@rorpage) if you have any questions! Also, please star the FaaS GitHub repo and read the introduction.