Search code examples
c#amazon-web-services.net-coreaws-lambdaamazon-sns

Read a SNS message at AWS Lambda Function written in C#


I have a lambda function at AWS written in c#. This lambda function would read an incoming SNS message. Below is my lambda code.

public void FunctionHandler(Amazon.Lambda.SNSEvents.SNSEvent.SNSMessage message, ILambdaContext context)
        {                  
            if (message.Message == null)
            {
                Console.WriteLine("message is null");
            }
            else if (message.Message == string.Empty)
            {
                Console.WriteLine("message is empty");
            }
            else
            {
              Console.WriteLine(message.Message);
            }
       }
    }

I have subscribed this lambda function to a SNS Topic. The lambda function is triggered when I publish the SNS message, but the message is always shown null. i.e the output I am getting is :

message is null

Can anyone help me in reading the SNS message?


Solution

  • From Amazon.Lambda.SNSEvents:

    public class Function
    {
        public string Handler(SNSEvent snsEvent)
        {
            foreach (var record in snsEvent.Records)
            {
                var snsRecord = record.Sns;
                Console.WriteLine($"[{record.EventSource} {snsRecord.Timestamp}] Message = {snsRecord.Message}");
            }
        }
    }
    

    So, it seems that SNSEvent contacts an array of Records, that contain Message.

    Start by changing your debug to print message instead of message.Message and take it from there.