我收到以下错误:
System.InvalidOperationException was unhandled by user code
HResult=-2146233079
Message=Operation is not valid due to the current state of the object.
Source=System.Windows
StackTrace:
at System.Net.Browser.ClientHttpWebRequest.InternalEndGetRequestStream(IAsyncResult asyncResult)
at System.Net.Browser.ClientHttpWebRequest.EndGetRequestStream(IAsyncResult asyncResult)
at SophosMobileControl.MainPage.<>c__DisplayClass5.<PushTestButton_Click>b__3(IAsyncResult ar)
at System.Net.Browser.ClientHttpWebRequest.<>c__DisplayClass18.<InvokeGetRequestStreamCallback>b__16(Object state2)
InnerException:
使用以下代码:
// Get the URI that the Microsoft Push Notification Service returns to the push client when creating a notification channel.
// Normally, a web service would listen for URIs coming from the web client and maintain a list of URIs to send
// notifications out to.
string subscriptionUri = (App.Current.Resources["Locator"] as ViewModelLocator).Main.PushUri;
HttpWebRequest sendNotificationRequest = (HttpWebRequest)WebRequest.Create(subscriptionUri);
// Create an HTTPWebRequest that posts the toast notification to the Microsoft Push Notification Service.
// HTTP POST is the only method allowed to send the notification.
sendNotificationRequest.Method = "POST";
// Create the toast message.
string toastMessage = "<?xml version=\"1.0\" encoding=\"utf-8\"?>" +
"<wp:Notification xmlns:wp=\"WPNotification\">" +
"<wp:Toast>" +
"<wp:Text1>" + "Title" + "</wp:Text1>" +
"<wp:Text2>" + "Subtitle" + "</wp:Text2>" +
"</wp:Toast> " +
"</wp:Notification>";
// Set the notification payload to send.
byte[] notificationMessage = Encoding.UTF8.GetBytes(toastMessage);
// Set the web request content length.
sendNotificationRequest.ContentLength = notificationMessage.Length;
sendNotificationRequest.ContentType = "text/xml";
//sendNotificationRequest.Headers["X-WindowsPhone-Target"] = "toast";
//sendNotificationRequest.Headers["X-NotificationClass"] = "2";
sendNotificationRequest.BeginGetRequestStream(ar =>
{
using (Stream postStream = sendNotificationRequest.EndGetRequestStream(ar))
{
postStream.Write(notificationMessage, 0, notificationMessage.Length);
}
}, sendNotificationRequest);
答案 0 :(得分:0)
我的解决方案是更改以下代码:
sendNotificationRequest.BeginGetRequestStream(ar =>
{
using (Stream postStream = sendNotificationRequest.EndGetRequestStream(ar))
{
postStream.Write(notificationMessage, 0, notificationMessage.Length);
}
}, sendNotificationRequest);
通过以下方式:
sendNotificationRequest.BeginGetRequestStream(new AsyncCallback(GetRequestStreamCallback), sendNotificationRequest);
void GetRequestStreamCallback(IAsyncResult callbackResult)
{
HttpWebRequest myRequest = (HttpWebRequest)callbackResult.AsyncState;
// End the stream request operation
Stream postStream = myRequest.EndGetRequestStream(callbackResult);
// Add the post data to the web request
postStream.Write(notificationMessage, 0, notificationMessage.Length);
postStream.Close();
}