Home > Mobile >  Why is my C# AWS Lambda not publishing my SNS message?
Why is my C# AWS Lambda not publishing my SNS message?

Time:02-14

I am new to C# and I am trying to build a handler function with Lambda to push messages to an SNS topic, this is what I have:

using MessagePublisher;

using Amazon.Lambda.Core;
using Amazon.SimpleNotificationService;
using Amazon.SimpleNotificationService.Model;


// Assembly attribute to enable the Lambda function's JSON input to be converted into a .NET class.
[assembly: LambdaSerializer(typeof(Amazon.Lambda.Serialization.SystemTextJson.DefaultLambdaJsonSerializer))]

namespace SNSMessagePublisher
{
    public class Function
    {
        public string PublishMessageHandler(NewMessage input, ILambdaContext context)
        {
            var client = new AmazonSimpleNotificationServiceClient(Amazon.RegionEndpoint.EUWest2);
            LambdaLogger.Log($"Calling function name: {context.FunctionName}\n");
            var publishRequest = new PublishRequest(
                "arn:aws:sns:eu-west-2:123...9:TopicABC",
                input.body);
            client.PublishAsync(publishRequest);
            return $"Message Published: {input.body}";
        }
    }
}
namespace MessagePublisher {
    public class NewMessage {
        public string body { get; set; }
    }
}

I then trigger a set payload of:

{
  "body": "test body"
}

and in the CloudWatch logs, I get an output of:

Calling function name: messagePublisher

And the Lambda console returns:

"Message Published: test body"

However, the topic never actually receives a message.

CodePudding user response:

client.PublishAsync(publishRequest); is asynchronous, will return a Task and as such, you need to wait on the task to finish executing using await.

Without calling await on the task, there is no guarantee that the client has published the message before the Lambda finishes executing.

The message is not being sent as the task for sending the message hasn't finished executing before the Lambda function has returned.

This should work:

public async Task<string> PublishMessageHandler(NewMessage input, ILambdaContext context)
{
    var client = new AmazonSimpleNotificationServiceClient(Amazon.RegionEndpoint.EUWest2);
    LambdaLogger.Log($"Calling function name: {context.FunctionName}\n");
    var publishRequest = new PublishRequest(
        "arn:aws:sns:eu-west-2:123...9:TopicABC",
        input.body);
    await client.PublishAsync(publishRequest);
    return $"Message Published: {input.body}";
}

As you're new to C#, I would recommend reading Microsoft's Asynchronous programming with async and await article.

  • Related