Your First Function: .NET

This guide takes you through the process of writing a Cloud Function using the .NET runtime language C#. There are two types of Cloud Functions:

  • An HTTP-triggered function, which you invoke from standard HTTP requests.
  • An event-driven function, which you use to handle events from your Cloud infrastructure, such as messages on a Cloud Pub/Sub topic, or changes in a Cloud Storage bucket.

Guide structure

  1. Creating a GCP project using Cloud SDK
  2. Creating a function
  3. Specifying dependencies
  4. Deploying the function
  5. Testing the deployed function
  6. Viewing logs
  7. Using Functions Framework

Creating a GCP project using Cloud SDK

  1. Sign in to your Google Cloud account. If you're new to Google Cloud, create an account to evaluate how our products perform in real-world scenarios. New customers also get $300 in free credits to run, test, and deploy workloads.
  2. In the Google Cloud Console, on the project selector page, select or create a Google Cloud project.

    Go to project selector

  3. Make sure that billing is enabled for your Cloud project. Learn how to confirm that billing is enabled for your project.

  4. Enable the Cloud Functions and Cloud Build APIs.

    Enable the APIs

  5. In the Google Cloud Console, on the project selector page, select or create a Google Cloud project.

    Go to project selector

  6. Make sure that billing is enabled for your Cloud project. Learn how to confirm that billing is enabled for your project.

  7. Enable the Cloud Functions and Cloud Build APIs.

    Enable the APIs

  8. Install and initialize the Cloud SDK.
  9. Update and install gcloud components:
    gcloud components update
  10. Prepare your development environment.

    Go to the .NET setup guide

Creating a function

This section describes how to manually create a function from scratch. Alternatively, you can use the templates provided by the template package.

To create a function:

  1. Create a directory on your local system for the function code:

    Windows

    mkdir %HOMEPATH%\helloworld
    cd %HOMEPATH%\helloworld
    

    Linux or Mac OS X

    mkdir ~/helloworld
    cd ~/helloworld
    
  2. Create a file called Function.cs with the contents below:

    using Google.Cloud.Functions.Framework;
    using Microsoft.AspNetCore.Http;
    using System.Threading.Tasks;
    
    namespace HelloWorld
    {
        public class Function : IHttpFunction
        {
            public async Task HandleAsync(HttpContext context)
            {
                await context.Response.WriteAsync("Hello World!");
            }
        }
    }

    This example function outputs the greeting "Hello World!"

Specifying dependencies

The next step is to set up dependencies. There are two different types of dependencies you can set up in C# Cloud Functions:

  • Make the Functions Framework available. That is the task you are doing in this section.
  • Make other libraries available, both in terms of project files and within the code via dependency injection. To learn more, see Customization through Functions Startup classes.

To make the Functions Framework available, change directory to the helloworld directory you created above:

     cd ~/helloworld

Then create a file called HelloWorld.csproj with the contents below:

<Project Sdk="Microsoft.NET.Sdk">
  <PropertyGroup>
    <OutputType>Exe</OutputType>
    <TargetFramework>netcoreapp3.1</TargetFramework>
  </PropertyGroup>

  <ItemGroup>
    <PackageReference Include="Google.Cloud.Functions.Hosting" Version="1.0.0" />
  </ItemGroup>
</Project>

Deploying the function

To deploy the function with an HTTP trigger, run the following command in the helloworld directory:

gcloud functions deploy my-first-function --entry-point HelloWorld.Function --runtime dotnet3 --trigger-http --allow-unauthenticated

where my-first-function is the registered name by which your function will be identified in the Cloud Console, and --entry-point specifies your function's fully qualified class name (FQN).

Testing the deployed function

  1. When the function finishes deploying, take note of the httpsTrigger.url property or find it using the following command:

    gcloud functions describe my-first-function
    

    It should look like this:

    https://GCP_REGION-PROJECT_ID.cloudfunctions.net/my-first-function
  2. Visit this URL in your browser. You should see a Hello World! message.

Viewing logs

Using the command-line tool

Logs for Cloud Functions are viewable in the Cloud Logging UI, and via the gcloud command-line tool.

To view logs for your function with the gcloud tool, use the logs read command, followed by the name of the function:

gcloud functions logs read my-first-function

The output should resemble the following:

LEVEL  NAME               EXECUTION_ID  TIME_UTC                 LOG
D      my-first-function  k2bqgroszo4u  2020-07-24 18:18:01.791  Function execution started
D      my-first-function  k2bqgroszo4u  2020-07-24 18:18:01.958  Function execution took 168 ms, finished with status code: 200
...

Using the Logging dashboard

You can also view logs for Cloud Functions from the Cloud Console.

Using the template package

The sections above tell you how to manually create a function from scratch. Going forward, you will likely use the templates to create new functions.

To use the templates to create, build, and test a function:

  1. Install .NET Core SDK 3.1.

  2. Install the template package:

    dotnet new -i Google.Cloud.Functions.Templates
    
  3. Next, create a directory for your project, and use dotnet new to create a new HTTP function:

    mkdir HelloFunctions
    cd HelloFunctions
    dotnet new gcf-http
    

    This creates HelloFunctions.csproj and Function.cs in the current directory. Open Function.cs to review the code, and provide a custom message if you want.

  4. Build your function locally as follows:

    dotnet run
    
  5. Once the server is running, browse to http://localhost:8080 to invoke the function. Press Ctrl-C in the console to stop the server.

    This function displays the message "Hello Functions Framework."

Alternatively, you can send requests to this function using curl from another terminal window:

curl localhost:8080
# Output: Hello Functions Framework