Create HTTP/HTTPS endpoint (listener) for SNS Topic using C# .NET !

aws_sns

Amazon Simple Notification Service (Amazon SNS) is a web service that enables applications, end-users, and devices to instantly send and receive notifications from the cloud.

A Topic is a communication channel to send messages and subscribe to notifications. It provides an access point for publishers and subscribers to communicate with each other.

For instructions on how to create a Topic – Click here

topic_subscriptions

In SNS Topic, there are multiple protocols (channels) supported which can be used as target for delivery of messages. The HTTP and HTTPS protocol options available can be used to deliver messages to a custom developed endpoint or a listener and used for processing of messages based on requirement.

We can create the endpoint in any language but here we are going to see how to create it in C# .NET.

When subscription is added to a Topic, two requests need to be handled-

  1. Subscription Confirmation : When a new subscription endpoint is added, SNS Topic sends a confirmation message to endpoint. The endpoint should return success response in order to get confirmed as a subscription on the Topic.
  2. Subscription Messages : Once the endpoint is confirmed, Topic will start delivering messages to the endpoint. Endpoint should be able to receive the messages, process them and send success response. If Topic does not receive success response, it will retry to send the message again to endpoint.

Below is the HttpPost method which handles both these use cases. Code can be modified to add additional logic for processing of messages based on requirement-

Pre-Requisites-

  • Create an MVC application with .NET version 4.5 or higher.
  • Add NuGet packages for AWSSDK.Core and AWSSDK.SimpleNotificationService in the solution

AWS_NuGet

Code Snippet-

Add an HttpPost method in the Controller –

[HttpPost]
public String SNSSubscriptionPost(String id="")
{
try
{
var jsonData = "";
Stream req = Request.InputStream;
req.Seek(0, System.IO.SeekOrigin.Begin);
String json = new StreamReader(req).ReadToEnd();
var sm = Amazon.SimpleNotificationService.Util.Message.ParseMessage(json);
if (sm.Type.Equals("SubscriptionConfirmation")) //for confirmation
{
logger.Info("Received Confirm subscription request");
if (!string.IsNullOrEmpty(sm.SubscribeURL))
{
var uri = new Uri(sm.SubscribeURL);
logger.Info("uri:" + uri.ToString());
var baseUrl = uri.GetLeftPart(System.UriPartial.Authority);
var resource = sm.SubscribeURL.Replace(baseUrl, "");
var response = new RestClient
{
BaseUrl = new Uri(baseUrl),
}.Execute(new RestRequest
{
Resource = resource,
Method = Method.GET,
RequestFormat = RestSharp.DataFormat.Xml
});
}
}
else // For processing of messages
{
logger.Info("Message received from SNS:"+sm.TopicArn);
dynamic message = JsonConvert.DeserializeObject(sm.MessageText);
logger.Info("EventTime : "+message.detail.eventTime);
logger.Info("EventName : " + message.detail.eventName);
logger.Info("RequestParams : " + message.detail.requestParameters);
logger.Info("ResponseParams : " + message.detail.responseElements);
logger.Info("RequestID : " + message.detail.requestID);
}
//do stuff
return "Success";
}
catch (Exception ex)
{
logger.Info("failed");
return "";
}
}

Now host this service on IIS with HTTP or HTTPS (SSL Cert) binding on a Windows Instance. Now either assign the hosted application a DNS or use Public IP to access it.

Example –

With Domain binding – https://sns-subspoc.techmanyu.com/SNSCode/SNS/SNSSubscriptionPost

With IP Address –  https://54.24.189.23/SNSCode/SNS/SNSSubscriptionPost

Once the endpoint is available, go to SNS Topic and add it as subscription-

CreateSubscription

The endpoint will receive request for confirmation and will respond will success. After that it will start receiving the messages (in JSON format). Check the method logs for verification of messages.

Thanks for checking out !

Please share , comment and like the post.

Categories
Comments
All comments.
Comments

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.

  1. kiran

    Hi Abhimanyu,
    Nice article. I did not get any subscription end point, so not able to confirm the subscription.
    Could you please help on this.

    Thanks

  2. Abhimanyu

    You will not receive any endpoint. Once you host the service on IIS on a system, you have to frame the endpoint based on the ip of host of your machine and the service /method you created. (it will not work from your local laptop or system. It has to have a public ip or host)
    Please email me if you have any other questions.

  3. saurabh

    Nice article, before hitting the endpoint.. how we can authenticate the URL hit by amazon itself.