Silverlight HTTP POST几个变量,最简单的例子(最少的代码)

6

你好,我想从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. }  
2个回答

7
您可以使用WebClient发送表单数据。如果您不关心成功确认,那么代码会非常简短:
WebClient wc = new WebClient();
wc.Headers["Content-type"] = "application/x-www-form-urlencoded";
wc.UploadStringAsync(new Uri(postUrl), "POST", "val1=param1&val2=param2");

3
哪一部分特别伤害了你的眼睛?代码太少了吗?你可以将所有这些内容都包装在一个带有事件的辅助类中,这样你就会拥有与AS示例相同的行数。而且没有flex示例,只有AS3示例 =)。AS3变体是相同的,只是被Adobe包装成单个类,并且只有一个回调函数在外部。我还想提醒你,这不是 - 旧好的同步请求,这是异步的,总是很丑(在我看来)。Silverlight中也没有同步网络,所以我认为你应该习惯它。

在C#中,您需要2个异步回调,在AS3中仅需要1个。由于发布数据与将内容打印到命令行一样普遍,因此我希望有一些帮助程序可以减少代码量... - Julian de Wit

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接