Silverlight HTTP POST少数变量,SIMPLEST示例(最少代码)

您好我想将一些来自silverlight的数据发布到网站上。
我发现以下链接 ,它的工作原理……
然而……这个例子太精致了,让我的眼睛受伤。
另外.. flex示例更干净/更少代码..

我想说必须有更好的解决方案……

供参考..我们发布2个变量(字符串)并读出结果(字符串)。

来自链接的解决方案:

1. // C# 2. // Create a request object 3. HttpWebRequest request = (HttpWebRequest)WebRequest.Create(new Uri(POST_ADDRESS, UriKind.Absolute)); 4. request.Method = "POST"; 5. // don't miss out this 6. request.ContentType = "application/x-www-form-urlencoded"; 7. request.BeginGetRequestStream(new AsyncCallback(RequestReady), request); 8. 9. // Sumbit the Post Data 10. void RequestReady(IAsyncResult asyncResult) 11. { 12. HttpWebRequest request = asyncResult.AsyncState as HttpWebRequest; 13. Stream stream = request.EndGetRequestStream(asyncResult); 14. 15. // Hack for solving multi-threading problem 16. // I think this is a bug 17. this.Dispatcher.BeginInvoke(delegate() 18. { 19. // Send the post variables 20. StreamWriter writer = new StreamWriter(stream); 21. writer.WriteLine("key1=value1"); 22. writer.WriteLine("key2=value2"); 23. writer.Flush(); 24. writer.Close(); 25. 26. request.BeginGetResponse(new AsyncCallback(ResponseReady), request); 27. }); 28. } 29. 30. // Get the Result 31. void ResponseReady(IAsyncResult asyncResult) 32. { 33. HttpWebRequest request = asyncResult.AsyncState as HttpWebRequest; 34. HttpWebResponse response = (HttpWebResponse)request.EndGetResponse(asyncResult); 35. 36. this.Dispatcher.BeginInvoke(delegate() 37. { 38. Stream responseStream = response.GetResponseStream(); 39. StreamReader reader = new StreamReader(responseStream); 40. // get the result text 41. string result = reader.ReadToEnd(); 42. }); 43. } 

您可以使用WebClient发送表单数据。 如果你不关心成功的确认,那将是非常短的:

 WebClient wc = new WebClient(); wc.Headers["Content-type"] = "application/x-www-form-urlencoded"; wc.UploadStringAsync(new Uri(postUrl), "POST", "val1=param1&val2=param2"); 

什么部分特别伤害你的眼睛? 更少的代码? 您可以使用event将所有这些包装在一个帮助器类中,并且您将在AS上具有与样本相同的行数。 并且没有flex样本,有AS3样本=)。 AS3变体是相同的,只是作为单个类包装(由adobe),只有一个回调。 而且我想提醒你,这不是 – 旧的良好同步请求,这是异步的,它总是那么难看(恕我直言)。 Silverlight中没有同步网络,所以我认为你应该习惯它。