2013-02-26 9 views
6

Próbuję dowiedzieć się, jak korzystać z pakietu AWS .NET SDK, aby potwierdzić subskrypcję tematu SNS.Przykładowe potwierdzenie subskrypcji SNS przy użyciu AWS .NET SDK

subskrypcja jest poprzez HTTP

Punkt końcowy będzie w MVC internetowej.

Nie mogę znaleźć żadnych przykładów .net w dowolnym miejscu?

Przykład pracy byłby fantastyczny.

próbuję coś jak to

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 

Odpowiedz

0

Skończyło się to działa przy użyciu kodu pokazany. Wystąpił problem podczas przechwytywania wyjątku na serwerze programistycznym, który okazał się informujący, że czas serwera nie pasuje do znacznika czasu w komunikacie SNS.

Po naprawieniu czasu serwera (serwer Amazon BTW) potwierdzenie zadziałało.

0

Poniższy przykład pomógł mi pracować z SNS. Przechodzi wszystkie etapy pracy z tematami. Żądanie subskrypcji w tym przypadku jest adresem e-mail, ale można go zmienić na HTTP.

Pavel's SNS Example
Documentation

+0

Dzięki, ale ten przykład nie obejmuje potwierdzenia subskrypcji za pośrednictwem protokołu HTTP, który jest specyficzny, z czym mam problem. –

9

Oto przykład działający przy użyciu MVC WebApi 2 i najnowszego pakietu SDK AWS .NET.

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; 
} 
1

Opierając się na @ odpowiedź Craiga powyżej (który pomógł mi ogromnie), poniżej jest kontroler ASP.NET MVC WebAPI dla czasochłonne i auto-subskrybowania tematy SNS. #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" }); 
     } 
    } 
    } 
} 
0

nie wiem jak ostatnio to się zmieniło, ale odkryłem, że AWS SNS teraz oferuje bardzo prosty sposób za subskrypcję, która nie wiąże wyodrębniania adresów URL lub żądania budynku za RESTSharp .. ... Oto uproszczona metoda POST WebApi:

[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" }); 
     } 
    }