开发者

Silverlight - Exception when trying to POST to webservice

I'm using the "Post" method so I can send a custom object. But I keep getting the following exception on the request.BeginGetResponse():

{System.Net.ProtocolViolationException: Operation is not valid due to the current state of the object. at System.Net.Browser.BrowserHttpWebRequest.BeginGetResponseImplementation()}

public void Send()
    {
        HttpWebRequest client = WebRequest.Create(new Uri(BaseUrl)) as HttpWebRequest;
        client.Method = "POST";
        client.ContentLength = MaxSerializationSize;
        client.BeginGetRequestStream(new AsyncCallback(RequestProceed), client);
    }

    private void RequestProceed(IAsyncResult asuncResult)
    {
        HttpWebRequest request = (HttpWebRequest) asuncResult.AsyncState;

        StreamWriter postDataWriter = new StreamWriter(request.EndGetRequestStream(asuncResult));
        MemoryStream ms = new MemoryStream();
        DataContractJsonSerializer ser = new     DataContractJsonSerializer(typeof(MyCustomClass));
        ser.WriteObject(ms, MyCustomClassObject);
        postDataWriter.Write(ms);
        postDataWriter.Close();

        request.BeginGetResponse(new AsyncCallback(ResponceProceed), request);

    }

    private void ResponceProceed(IAsyncResult asuncResult)
    {
        var request = (HttpWebRequest) asuncResult.AsyncState;

        using (var resp = (HttpWebResponse) request.EndGetResponse(asuncResult))
        {
            using (var stre开发者_如何学Cam = resp.GetResponseStream())
            {
            }
        }
    }

I have tried so many ways to get this to work. Hoping someone can tell me where i'm going wrong. Thanks.


You need to close the request stream. You are just closing the StreamWriter and not the underlying request stream. While you are at it eliminate the superflous MemoryStream and have the DataContractJsonSerializer write directly to the Request stream.

 HttpWebRequest request = (HttpWebRequest) asuncResult.AsyncState;

 using (Stream outStream = request.EndGetRequestStream(asyncResult));
 {
      DataContractJsonSerializer ser = new     DataContractJsonSerializer(typeof(MyCustomClass));           
      ser.WriteObject(outStream, MyCustomClassObject);
      outStream.Flush();
      outStream.Close();
 }

 request.BeginGetResponse(new AsyncCallback(ResponceProceed), request); 

Also get rid of this line:-

 client.ContentLength = MaxSerializationSize; 

Without also turning off AllowWriteStreamBuffering (which is only possible on the ClientHTTP implementation anyway) there is no need to set the ContentLength, that is done for you.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜