【发布时间】:2020-06-04 21:04:08
【问题描述】:
这个问题可能已经被问过很多次了,但他们的solution 没有一个真正有帮助。
我正在使用 OneSignal 向所有连接的客户端发送推送通知。我在服务中实现了代码并将其设为单例。
我想要什么
我的用例是我想向用户发送通知,并立即向另一个用户发送不同的通知。
问题
它仅适用于第一个请求,之后,我不断收到此错误:
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
这里是实现:
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
}
}
}
【问题讨论】:
-
我不得不提一下,我尝试将此服务添加为 Transient,并且成功了。但是,我认为这不是一个长期的解决方案,因为必须为每个请求重新初始化
-
我知道这不是一个直接的答案,但是当您使用 asp net core 时,我建议您通过 IHttpClientFactory 使用 HttpClient 并使用依赖注入。
标签: c# asp.net asp.net-mvc asp.net-core onesignal