Asp.net-Mvc

使用 AWS .NET SDK 的範例 SNS 訂閱確認

  • June 7, 2019

我試圖弄清楚如何使用 AWS .NET SDK 來確認訂閱 SNS 主題。

訂閱是通過 HTTP

端點將位於 .net mvc 網站中。

我在任何地方都找不到任何 .net 範例?

一個工作的例子會很棒。

我正在嘗試這樣的事情

Dim snsclient As New Amazon.SimpleNotificationService.AmazonSimpleNotificationServiceClient(ConfigurationSettings.AppSettings("AWSAccessKey"), ConfigurationSettings.AppSettings("AWSSecretKey"))

   Dim TopicArn As String = "arn:aws:sns:us-east-1:991924819628:post-delivery"


   If Request.Headers("x-amz-sns-message-type") = "SubscriptionConfirmation" Then

       Request.InputStream.Seek(0, 0)
       Dim reader As New System.IO.StreamReader(Request.InputStream)
       Dim inputString As String = reader.ReadToEnd()

       Dim jsSerializer As New System.Web.Script.Serialization.JavaScriptSerializer
       Dim message As Dictionary(Of String, String) = jsSerializer.Deserialize(Of Dictionary(Of String, String))(inputString)

       snsclient.ConfirmSubscription(New Amazon.SimpleNotificationService.Model.ConfirmSubscriptionRequest With {.AuthenticateOnUnsubscribe = False, .Token = message("Token"), .TopicArn = TopicArn})


  End If

這是一個使用 MVC WebApi 2 和最新 AWS .NET SDK 的工作範例。

var jsonData = Request.Content.ReadAsStringAsync().Result;
var snsMessage = Amazon.SimpleNotificationService.Util.Message.ParseMessage(jsonData);

//verify the signaure using AWS method
if(!snsMessage.IsMessageSignatureValid())
   throw new Exception("Invalid signature");

if(snsMessage.Type == Amazon.SimpleNotificationService.Util.Message.MESSAGE_TYPE_SUBSCRIPTION_CONFIRMATION)
{
   var subscribeUrl = snsMessage.SubscribeURL;
   var webClient = new WebClient();
   webClient.DownloadString(subscribeUrl);
   return "Successfully subscribed to: " + subscribeUrl;
}

基於上面@Craig 的回答(這對我有很大幫助),下面是一個用於消費和自動訂閱SNS 主題的ASP.NET MVC WebAPI 控制器。#WebHooksFTW

using RestSharp;
using System;
using System.Net;
using System.Net.Http;
using System.Reflection;
using System.Web.Http;
using System.Web.Http.Description;

namespace sb.web.Controllers.api {
 [System.Web.Mvc.HandleError]
 [AllowAnonymous]
 [ApiExplorerSettings(IgnoreApi = true)]
 public class SnsController : ApiController {
   private static string className = MethodBase.GetCurrentMethod().DeclaringType.Name;

   [HttpPost]
   public HttpResponseMessage Post(string id = "") {
     try {
       var jsonData = Request.Content.ReadAsStringAsync().Result;
       var sm = Amazon.SimpleNotificationService.Util.Message.ParseMessage(jsonData);
       //LogIt.D(jsonData);
       //LogIt.D(sm);

       if (!string.IsNullOrEmpty(sm.SubscribeURL)) {
         var uri = new Uri(sm.SubscribeURL);
         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
         });
         if (response.StatusCode != System.Net.HttpStatusCode.OK) {
           //LogIt.W(response.StatusCode);
         } else {
           //LogIt.I(response.Content);
         }
       }

       //read for topic: sm.TopicArn
       //read for data: dynamic json = JObject.Parse(sm.MessageText);
       //extract value: var s3OrigUrlSnippet = json.input.key.Value as string;

       //do stuff
       return Request.CreateResponse(HttpStatusCode.OK, new { });
     } catch (Exception ex) {
       //LogIt.E(ex);
       return Request.CreateResponse(HttpStatusCode.InternalServerError, new { status = "unexpected error" });
     }
   }
 }
}

引用自:https://stackoverflow.com/questions/15079829