Writing and Responding to Pub/Sub Messages

Google Cloud Pub/Sub provides reliable, many-to-many, asynchronous messaging between applications. Publisher applications can send messages to a topic, and other applications can subscribe to that topic to receive the messages.

This document describes how to use the Google Cloud Client Library to send and receive Google Cloud Pub/Sub messages in an app running in the flexible environment.

Prerequisites

  • Follow the instructions in "Hello, World!" for .NET on App Engine to set up your environment and project, and to understand how App Engine .NET apps are structured.
  • Write down and save your project ID, because you will need it to run the sample application described in this document.
  • To download credentials from the Google Cloud Platform Console to create a service account and add the service account key to your application, follow step 3 outlined on GitHub.
  • Enable the Google Cloud Pub/Sub API.

    Enable the API

Clone the sample app

Copy the sample apps to your local machine, and navigate to the pubsub directory:

git clone https://github.com/GoogleCloudPlatform/dotnet-docs-samples
cd dotnet-docs-samples/appengine/flexible/pubsub

Create a topic and subscription

Create a topic and subscription, which includes specifying the endpoint to which the Pub/Sub server should send requests:

gcloud pubsub topics create YOUR_TOPIC
gcloud pubsub subscriptions create YOUR_SUBSCRIPTION `
    --topic YOUR_TOPIC `
    --push-endpoint `
    https://YOUR_PROJECT_ID.appspot.com/pubsub/push?token=YOUR_SECRET_TOKEN `
    --ack-deadline 10

Edit appsettings.json

Edit appsettings.json to set your project ID:

{
  "Pubsub": {
    "ProjectId": "your-project-id",
    "VerificationToken": "your-secret-token",
    "TopicId": "your-topic",
    "SubscriptionId": "your-subscription"
  },
  
  "Logging": {
    "IncludeScopes": false,
    "LogLevel": {
      "Default": "Debug",
      "System": "Information",
      "Microsoft": "Information"
    }
  }
}

Code review

The sample app uses the Google Cloud Client Libraries.

[HttpGet]
[HttpPost]
public IActionResult Index(MessageForm messageForm)
{
    var model = new MessageList();
    if (!string.IsNullOrEmpty(messageForm.Message))
    {
        // Publish the message.
        var topicName = new TopicName(_options.ProjectId, 
            _options.TopicId);
        var pubsubMessage = new PubsubMessage()
        {
            Data = ByteString.CopyFromUtf8(messageForm.Message)
        };
        pubsubMessage.Attributes["token"] = _options.VerificationToken;
        _publisher.Publish(topicName, new[] { pubsubMessage });
        model.PublishedMessage = messageForm.Message;
    }
    // Render the current list of messages.
    lock (s_lock) model.Messages = s_receivedMessages.ToArray();
    return View(model);
}

Run the sample locally

When running locally, you can use the Google Cloud SDK to provide authentication to use Google Cloud APIs. Assuming you set up your environment as described in Prerequisites, you have already run the gcloud init command, which provides this authentication.

To run the sample app locally:

Visual Studio

  1. Open dotnet-docs-samples\appengine\flexible\AppEngineFlex.sln with Visual Studio.

  2. In Solution Explorer, right-click Pubsub, and choose Debug > Start new instance.

Command line

  1. Run the following commands from the dotnet-docs-samples\appengine\flexible\Pubsub directory:

    dotnet restore
    dotnet run
    
  2. In your web browser, enter the following address:

    http://localhost:5000/
    

Simulate push notifications

The application can send messages locally, but it is not able to receive push messages locally. You can, however, simulate a push message by making an HTTP request to the local push notification endpoint. The sample includes the file sample_message.json.

To send an HTTP POST request:

Get-Content -Raw .\sample_message.json | Invoke-WebRequest -Uri
http://localhost:5000/Push?token=your-secret-token -Method POST -ContentType
'text/json' -OutFile out.txt

After the request completes, you can refresh localhost:5000 and see the message in the list of received messages.

Run on App Engine

To deploy the demo app to App Engine by using the gcloud command-line tool, you run the following command from the directory where your app.yaml is located:

Visual Studio

To deploy the Hello World app:

  1. Open dotnet-docs-samples\appengine\flexible\AppEngineFlex.sln with Visual Studio.
  2. In Solution Explorer, right-click Pubsub, and choose Publish to Google Cloud...
  3. Click App Engine Flex.
  4. Click Publish.

Command line

Run the following commands from the dotnet-docs-samples\appengine\flexible\Pubsub directory:
dotnet restore
dotnet publish
cd bin\Debug\netcoreapp2.1\publish
gcloud app deploy

You can now access the application at https://[YOUR_PROJECT_ID].appspot.com. You can use the form to submit messages, but there's no guarantee of which instance of your application will receive the notification. You can send multiple messages and refresh the page to see the received message.

Was this page helpful? Let us know how we did:

Send feedback about...

App Engine flexible environment for .NET docs