Silverlight:Web服务调用JSON错误

时间:2012-02-28 17:27:53

标签: c# json silverlight web-services asynchronous

好的,所以我不知道为什么这不起作用。我发现了4个在Silverlight中异步调用JSON Web服务的不同教程/示例,并且它们都使用与我相同的格式/逻辑。在“using(streamCommunities = request.EndGetRequestStream(asyncResult))”行中,它抛出了我附加在底部的错误,ArgumentException表示它不喜欢asyncResult。如果我发现的每个其他例子使用相同的逻辑,为什么会这样?

    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上找到答案,我感到困惑和沮丧。

- 提前谢谢 RJ

2 个答案:

答案 0 :(得分: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);

答案 1 :(得分:0)

你错了。 Ur使用BeginGetResponse。我在ACW遇到了同样的问题。将其更改为BeginGetRequestStream,一切都很好:)