0

so basically i'm using this

public static async void postToPushNotifcationAsync(String deviceId, String message, String title)
    {
        var serverKey = "";
        var senderId = "";

        var fcm = new FCMJsonModel();
        var fcmNotification = new FCMNotificationModel();


        fcmNotification.body = message;
        fcmNotification.title = title;
        fcmNotification.sound = "sound.caf";
        fcm.to = deviceId;
        fcm.notification = fcmNotification;

        var json = fcm.ToJSON();

        var content = new StringContent(json);
        content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/json");

        client.DefaultRequestHeaders.TryAddWithoutValidation("Authorization", "key=" + serverKey);
        client.DefaultRequestHeaders.TryAddWithoutValidation("Sender", "id=" + senderId);
        //client.Timeout = TimeSpan.FromMinutes(2);

        var cts = new CancellationTokenSource();
        cts.CancelAfter(TimeSpan.FromMinutes(1));

        var response = await client.PostAsync("https://fcm.googleapis.com/fcm/send", content, cts.Token);

        var responseString = await response.Content.ReadAsStringAsync();
    }
}

This method is basically posting a push notification server and send a message.I used this method multiple times for different api's but the post gets cluttered and it sends the first one and doesn't send the other ones. I just want to use this method multiple times and i'm even willing to not use async on this but it won't allow me to. I'm not an expert on ASP.NET programming but I would like to know how this can be fixed. Thank you for your help.

Jovin
  • 49
  • 2
  • 4
  • Are you sure the connection is kept alive? – PepitoSh Jun 11 '18 at 08:19
  • I agree with @PepitoSh. you do not show the code for the client, and that is probably where your problem lies. also, if you are reusing the same client, i am not sure if you should add the "Authorization" and "Sender" headers again, since you already added them when you called the method the first time. Lastly, you do not have to serialize your class to json yourself, just use "PostAsJsonAsync" see: https://stackoverflow.com/questions/15205389/get-response-from-postasjsonasync – Gerrie Pretorius Jun 11 '18 at 08:40
  • I have a global client declared like this private static readonly HttpClient client = new HttpClient(); – Jovin Jun 11 '18 at 08:50
  • @GerriePretorius that .toJson method actually returns a string like json. – Jovin Jun 11 '18 at 08:52
  • @Jovin exactly, you do not need to make it a string your self, you just have to pass the object, and let dot net make it a string for you. in my opinion its just cleaner to let dot net handle that, instead of you trying to stringify it yourself. – Gerrie Pretorius Jun 11 '18 at 10:12

0 Answers0