2012-02-28 22 views
0

好的,所以我不知道爲什麼這不起作用。我發現了4個不同的教程/在Silverlight中異步調用JSON Web服務的示例,並且它們都使用與我一樣的格式/邏輯。在「using(streamCommunities = request.EndGetRequestStream(asyncResult))」這一行,它拋出我附在底部的錯誤,一個ArgumentException表示它不喜歡asyncResult。爲什麼如果我發現的其他示例使用相同的邏輯呢?Silverlight:Web服務調用JSON錯誤

private void GetSource(object state) 
    { 
    HttpWebRequest request = (HttpWebRequest)WebRequest.Create(new Uri(MyValidUri)); 
    request.Method = "POST"; 
    request.ContentType = "application/json"; 
    request.BeginGetResponse(new AsyncCallback(ReadCommunityCallBack), request); 
    } 

    private void ReadCommunityCallBack(IAsyncResult asyncResult) 
    {    
     HttpWebRequest request = (HttpWebRequest)asyncResult.AsyncState; 

     using (Stream outStream = request.EndGetRequestStream(asyncResult)) 
     { 
      // DO STUFF HERE 
     } 
    } 

和錯誤是在這裏:

System.ArgumentException was unhandled by user code 
Message=Value does not fall within the expected range. 
    StackTrace: 
    at System.Net.Browser.ClientHttpWebRequest.EndGetRequestStream(IAsyncResult asyncResult) 
    at cenTabbedFeed.MainPage.ReadCommunityCallBack(IAsyncResult asyncResult) 
    at System.Net.Browser.ClientHttpWebRequest.<>c__DisplayClass1a.<InvokeGetResponseCallback>b__18(Object state2) 
    at System.Threading.QueueUserWorkItemCallback.WaitCallback_Context(Object state) 
    at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx) 
    at System.Threading.QueueUserWorkItemCallback.System.Threading.IThreadPoolWorkItem.ExecuteWorkItem() 
    at System.Threading.ThreadPoolWorkQueue.Dispatch() 
    at System.Threading._ThreadPoolWaitCallback.PerformWaitCallback() 

就像我說的,我已經沖刷的例子,並試圖找到在MSDN上的答案,我堅持和沮喪。

-Thanks提前 RJ

+0

嘗試通過將它放置在try/catch塊中來捕獲異常。該錯誤消息告訴您沒有捕獲錯誤。如果你抓住它,也許你有更多的信息。 – 2012-02-28 17:37:34

+0

但是也許你有更多關於它的信息。問題可能出現在服務器端。 – 2012-02-28 17:39:32

+0

它告訴我,我發佈的錯誤... e.Message =值不在預期範圍內。這並不能解決錯誤。 – 2012-02-28 17:43:02

回答

1

您的要求的方法是POST但你不張貼任何。請寫一些東西到RequestStream或改變你的方法到GET

- 編輯 -

您可以張貼一些字符串到服務器,如下

byte[] buf = Encoding.UTF8.GetBytes("key=value&key2=value2&key3=value3"); 
request.ContentType = "application/www-form-urlencoded"; 
request.ContentLength = buf.Length; 
request.GetRequestStream().Write(buf,0,buf.Length); 
+0

所以我有一個自定義類與發佈數據,我怎麼寫它的請求流? StreamWriter類和ToString()方法? – 2012-02-28 18:55:19

+0

要發佈內容,您必須將正文添加到請求中。它就像一個查詢字符串:key = value&key2 = value2&key3 = value3。該框架已經爲您抽象了流處理。 – 2012-02-28 19:01:48

+0

@ rjcup3,我更新了我的答案 – 2012-02-28 19:03:00

0

UVE找錯了一個。 Ur使用BeginGetResponse。我在ACW中遇到同樣的問題。改爲BeginGetRequestStream而不是,一切都很好:)

+0

不,實際上是因爲我笨拙,不知道如何使用WebRequest和POST方法。 BeginGetResponse是我在完成時使用的。它正在寫入流和通過狀態,我搞亂了。 – 2012-04-24 12:31:54