8

我试图弄清楚如何使用 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
4

5 回答 5

10

这是一个使用 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;
}
于 2015-05-27T18:16:55.527 回答
1

基于上面@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" });
      }
    }
  }
}
于 2016-05-18T01:35:44.937 回答
1

我不知道最近这种情况发生了怎样的变化,但我发现 AWS SNS 现在提供了一种非常简单的订阅方法,它不涉及使用 RESTSharp 提取 url 或构建请求.....这是简化的 WebApi POST 方法:

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

            if (sm.IsSubscriptionType)
            {
                sm.SubscribeToTopic(); // CONFIRM THE SUBSCRIPTION
            }
            if (sm.IsNotificationType) // PROCESS NOTIFICATIONS
            {
                //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" });
        }
    }
于 2017-02-22T10:42:27.883 回答
-1

以下示例帮助我使用 SNS。它经历了使用主题的所有步骤。在这种情况下,订阅请求是一个电子邮件地址,但是可以将其更改为 HTTP。

Pavel 的 SNS 示例
文档

于 2013-02-26T14:13:04.323 回答
-1

我最终使用显示的代码让它工作。我在开发服务器上捕获异常时遇到问题,结果告诉我服务器的时间与 SNS 消息中的时间戳不匹配。

一旦服务器的时间确定(顺便说一句亚马逊服务器),确认工作。

于 2013-02-28T01:57:04.950 回答