This question probably has been asked multiple times, but none of their solution really helped.
I am using OneSignal to send push notifications to all connected clients. I implemented the code in a service and made it a Singleton.
What I want
My use case is that I want to send a notification to a user, and immediately send a different notification to another user.
Problem
It works only for the first request, after that, I keep getting this error:
System.InvalidOperationException: This operation cannot be performed after the request has been submitted.
at System.Net.HttpWebRequest.InternalGetRequestStream()
at System.Net.HttpWebRequest.GetRequestStream()
at BingoAPI.Services.NotificationService.SendNotificationAsync(Byte[] buffer) in D:\Bingo\BingoAPI\Services\NotificationService.cs:line 74
Here is the implementation:
public NotificationService(IOptions<OneSignalNotificationSettigs> oneSignalSettings, IOptions<NotificationTemplates> notificationTemplates)
{
this.oneSignalSettings = oneSignalSettings;
this.notificationTemplates = notificationTemplates;
// request configuration
request = WebRequest.Create(oneSignalSettings.Value.EndPoint) as HttpWebRequest;
request.Headers.Add("authorization", oneSignalSettings.Value.Authorization);
request.KeepAlive = true;
request.Method = "POST";
request.ContentType = "application/json; charset=utf-8";
}
private async Task SendNotificationAsync(byte[] buffer)
{
string responseContent = null;
try
{
// here is the error
var writer = await request.GetRequestStreamAsync();
await writer.WriteAsync(buffer, 0, buffer.Length);
writer.Close();
var response = await request.GetResponseAsync() as HttpWebResponse;
var reader = new StreamReader(response.GetResponseStream());
responseContent = await reader.ReadToEndAsync();
}
catch (WebException ex)
{
// LOGGING
}
}
}