Si vous créez une fonction, consultez le guide de démarrage rapide de la console sur Cloud Run. Le contenu de cette page ne s'applique qu'aux anciennes fonctions existantes créées avec l'API Cloud Functions v1.
Restez organisé à l'aide des collections
Enregistrez et classez les contenus selon vos préférences.
Langages .NET
Il est possible d'écrire une fonction dans différents langages .NET (C#, Visual Basic ou F#). Commune à tous les langages, la tâche de base consiste à créer une classe mettant en œuvre l'une des interfaces du framework des fonctions :
dotnet new install Google.Cloud.Functions.Templates
Des modèles sont fournis pour les trois types de fonctions en C# (par défaut), F# et Visual Basic. Lorsque vous créez un projet à partir d'un modèle, spécifiez -lang f# pour créer un projet F# ou -lang vb pour créer un projet Visual Basic. Par exemple, pour créer une fonction CloudEvent sans type pour Visual Basic, exécutez la commande suivante :
dotnetnewgcf-untyped-event-langvb
Exemples de fonctions HTTP
Les fonctions HTTP vous permettent d'appeler votre fonction via une requête HTTP(S). Les exemples suivants génèrent le message "Hello World!".
Utilisez les fonctions CloudEvent lorsque vous souhaitez que votre fonction Cloud Run soit appelée indirectement en réponse à un événement asynchrone, tel qu'un message sur un sujet Pub/Sub, une modification dans un bucket Cloud Storage ou un événement Firebase.
Vous pouvez tester les exemples de fonctions CloudEvent comme suit :
Publiez un message sur votre sujet Pub/Sub pour déclencher votre fonction :
gcloudpubsubtopicspublishmy-topic--messageFlurry
Examinez les journaux :
gcloudfunctionslogsread--limit10
Un message semblable au suivant doit s'afficher, contenant le nom que vous avez publié dans le sujet Pub/Sub :
D my-function ... Function execution started
I my-function ... Hello Flurry!
D my-function ... Function execution took 39 ms, finished with status: 'ok'
Sauf indication contraire, le contenu de cette page est régi par une licence Creative Commons Attribution 4.0, et les échantillons de code sont régis par une licence Apache 2.0. Pour en savoir plus, consultez les Règles du site Google Developers. Java est une marque déposée d'Oracle et/ou de ses sociétés affiliées.
Dernière mise à jour le 2025/09/03 (UTC).
[[["Facile à comprendre","easyToUnderstand","thumb-up"],["J'ai pu résoudre mon problème","solvedMyProblem","thumb-up"],["Autre","otherUp","thumb-up"]],[["Difficile à comprendre","hardToUnderstand","thumb-down"],["Informations ou exemple de code incorrects","incorrectInformationOrSampleCode","thumb-down"],["Il n'y a pas l'information/les exemples dont j'ai besoin","missingTheInformationSamplesINeed","thumb-down"],["Problème de traduction","translationIssue","thumb-down"],["Autre","otherDown","thumb-down"]],["Dernière mise à jour le 2025/09/03 (UTC)."],[[["\u003cp\u003e.NET functions can be written in C#, Visual Basic, or F#, all requiring the implementation of either the \u003ccode\u003eIHttpFunction\u003c/code\u003e, generic \u003ccode\u003eICloudEvent<T>\u003c/code\u003e, or non-generic \u003ccode\u003eICloudEvent\u003c/code\u003e interface.\u003c/p\u003e\n"],["\u003cp\u003eTemplates for creating .NET function projects in C#, F#, and Visual Basic can be installed via the command \u003ccode\u003edotnet new install Google.Cloud.Functions.Templates\u003c/code\u003e, using \u003ccode\u003e-lang f#\u003c/code\u003e or \u003ccode\u003e-lang vb\u003c/code\u003e to generate the desired language.\u003c/p\u003e\n"],["\u003cp\u003eHTTP functions are invoked by HTTP(S) requests and shown through F# and Visual Basic examples that output "Hello World!".\u003c/p\u003e\n"],["\u003cp\u003eCloudEvent functions are triggered by asynchronous events, demonstrated with F# and Visual Basic examples responding to a message on a Pub/Sub topic.\u003c/p\u003e\n"],["\u003cp\u003eCloudEvent function testing involves publishing a message to a Pub/Sub topic and checking the logs to see if the function was triggered and what the output is.\u003c/p\u003e\n"]]],[],null,["# .NET Languages\n==============\n\nIt's possible to write your function in using different .NET languages (C#,\nVisual Basic, or F#). The core task is the same in all languages---you\ncreate a class implementing one of the Functions Framework interfaces:\n\n- [IHttpFunction](https://github.com/GoogleCloudPlatform/functions-framework-dotnet/blob/master/src/Google.Cloud.Functions.Framework/IHttpFunction.cs)\n- The generic [ICloudEvent\u003cT\u003e](https://github.com/GoogleCloudPlatform/functions-framework-dotnet/blob/master/src/Google.Cloud.Functions.Framework/ICloudEventFunction.cs)\n- The non-generic [ICloudEvent](https://github.com/GoogleCloudPlatform/functions-framework-dotnet/blob/master/src/Google.Cloud.Functions.Framework/ICloudEventFunction.cs)\n\nThis document provides examples for F# and Visual Basic.\n\nTemplates\n---------\n\nNote that to run the examples in this document, you will use the\n[templates](https://github.com/GoogleCloudPlatform/functions-framework-dotnet#functions-framework-for-net):\n\n1. Install the [.NET SDK](https://dotnet.microsoft.com/download).\n\n2. Install the template package:\n\n dotnet new install Google.Cloud.Functions.Templates\n\n| **Note:** versions of the .NET SDK earlier than .NET 7 use `dotnet new -i` instead of `dotnet new install`.\n\nTemplates are provided for the three kinds of functions in C# (the default), F#,\nand Visual Basic. When creating a new project from a template, specify\n`-lang f#` to create an F# project, or `-lang vb` to create a Visual Basic\nproject. For example, to create a new untyped CloudEvent function for Visual\nBasic, you would run: \n\n dotnet new gcf-untyped-event -lang vb\n\n| **Note:** `Function` is a keyword in Visual Basic, so for Visual Basic, the templates create a class with the name `CloudFunction`.\n\nHTTP function examples\n----------------------\n\nYou use [HTTP functions](/functions/1stgendocs/writing/write-http-functions) when you want to invoke\nyour function via an HTTP(S) request. The following examples output the message\n`\"Hello World!\"` \n\n### F#\n\n```f#\nnamespace HelloWorldFSharp\n\nopen Google.Cloud.Functions.Framework\nopen Microsoft.AspNetCore.Http\n\ntype Function() =\n interface IHttpFunction with\n member this.HandleAsync context =\n async {\n do! context.Response.WriteAsync \"Hello World!\" |\u003e Async.AwaitTask\n } |\u003e Async.StartAsTask :\u003e _\n```\n\n### Visual Basic\n\n```vb.net\nImports Google.Cloud.Functions.Framework\nImports Microsoft.AspNetCore.Http\n\nPublic Class CloudFunction\n Implements IHttpFunction\n\n Public Async Function HandleAsync(context As HttpContext) As Task Implements IHttpFunction.HandleAsync\n Await context.Response.WriteAsync(\"Hello World!\")\n End Function\nEnd Class\n```\n\n### Project files for HTTP examples\n\nHere are the project files for the above samples: \n\n### F#\n\n```f#\n\u003cProject Sdk=\"Microsoft.NET.Sdk\"\u003e\n \u003cPropertyGroup\u003e\n \u003cOutputType\u003eExe\u003c/OutputType\u003e\n \u003cTargetFramework\u003enet6.0\u003c/TargetFramework\u003e\n \u003c/PropertyGroup\u003e\n\n \u003cItemGroup\u003e\n \u003cCompile Include=\"Function.fs\" /\u003e\n \u003c/ItemGroup\u003e\n\n \u003cItemGroup\u003e\n \u003cPackageReference Include=\"Google.Cloud.Functions.Hosting\" Version=\"2.2.1\" /\u003e\n \u003c/ItemGroup\u003e\n\u003c/Project\u003e\n```\n\n### Visual Basic\n\n```vb.net\n\u003cProject Sdk=\"Microsoft.NET.Sdk\"\u003e\n \u003cPropertyGroup\u003e\n \u003cOutputType\u003eExe\u003c/OutputType\u003e\n \u003cRootNamespace\u003eHelloWorldVb\u003c/RootNamespace\u003e\n \u003cTargetFramework\u003enet6.0\u003c/TargetFramework\u003e\n \u003c/PropertyGroup\u003e\n\n \u003cItemGroup\u003e\n \u003cPackageReference Include=\"Google.Cloud.Functions.Hosting\" Version=\"2.2.1\" /\u003e\n \u003c/ItemGroup\u003e\n\u003c/Project\u003e\n```\n\n### Deploying the HTTP functions\n\n### F#\n\n gcloud functions deploy fsharp-helloworld --no-gen2 --entry-point HelloWorldFSharp.Function --runtime dotnet6 --trigger-http --allow-unauthenticated\n\n### Visual Basic\n\n gcloud functions deploy vb-helloworld --no-gen2 --entry-point HelloWorldVb.CloudFunction --runtime dotnet6 --trigger-http --allow-unauthenticated\n\nCloudEvent examples\n-------------------\n\nYou use [CloudEvent functions](https://github.com/GoogleCloudPlatform/functions-framework-dotnet#cloud-event-functions) when you want\nto have your Cloud Run function invoked indirectly in response to an asynchronous\nevent, such as a message on a Pub/Sub topic, a change in a Cloud Storage bucket,\nor a Firebase event. \n\n### F#\n\n```f#\nnamespace HelloPubSubFSharp\n\nopen Google.Cloud.Functions.Framework\nopen Google.Events.Protobuf.Cloud.PubSub.V1\nopen Microsoft.Extensions.Logging\nopen System\nopen System.Threading.Tasks\n\ntype Function(logger: ILogger\u003cFunction\u003e) =\n interface ICloudEventFunction\u003cMessagePublishedData\u003e with\n member this.HandleAsync(cloudEvent, data, cancellationToken) =\n let nameFromMessage = data.Message.TextData\n let name = if String.IsNullOrEmpty(nameFromMessage) then \"world\" else nameFromMessage\n logger.LogInformation(\"Hello {name}\", name)\n Task.CompletedTask\n```\n\n### Visual Basic\n\n```vb.net\nImports System.Threading\nImports CloudNative.CloudEvents\nImports Google.Cloud.Functions.Framework\nImports Google.Events.Protobuf.Cloud.PubSub.V1\nImports Microsoft.Extensions.Logging\n\nPublic Class CloudFunction\n Implements ICloudEventFunction(Of MessagePublishedData)\n\n Private _logger As ILogger\n\n Public Sub New(ByVal logger As ILogger(Of CloudFunction))\n _logger = logger\n End Sub\n\n\n Public Function HandleAsync(cloudEvent As CloudEvent, data As MessagePublishedData, cancellationToken As CancellationToken) As Task _\n Implements ICloudEventFunction(Of MessagePublishedData).HandleAsync\n\n Dim nameFromMessage = data.Message?.TextData\n Dim name = If(String.IsNullOrEmpty(nameFromMessage), \"world\", nameFromMessage)\n _logger.LogInformation(\"Hello {name}\", name)\n\n Return Task.CompletedTask\n End Function\nEnd Class\n```\n\n### Deploying the CloudEvent functions\n\n### F#\n\n gcloud functions deploy fsharp-hello-pubsub --no-gen2 --entry-point HelloPubSubFSharp.Function --runtime dotnet6 --trigger-topic my-topic --allow-unauthenticated\n\n### Visual Basic\n\n gcloud functions deploy vb-hello-pubsub --no-gen2 --entry-point HelloPubSubVb.CloudFunction --runtime dotnet6 --trigger-topic my-topic --allow-unauthenticated\n\n### Test the CloudEvent examples\n\nYou can test the CloudEvent examples as follows:\n\n1. Publish a message to your Pub/Sub topic to trigger your function:\n\n ```bash\n gcloud pubsub topics publish my-topic --message Flurry\n ```\n2. Look at the logs:\n\n ```bash\n gcloud functions logs read --limit 10\n ```\n\nYou should see something like this, with a message that includes the name you\npublished to the Pub/Sub topic: \n\n D my-function ... Function execution started\n I my-function ... Hello Flurry!\n D my-function ... Function execution took 39 ms, finished with status: 'ok'\n\n| **Note:** log messages may be delayed by a few minutes."]]