質問

I'm trying to get some data back from rest WS in C# but I'm getting this error:

You must write ContentLength bytes to the request stream before calling [Begin]GetResponse.

This is the code I'm trying to use:

var json = new JavaScriptSerializer().Serialize(order);
        string jsonResponseToString = "";
        HttpWebRequest request =
            (HttpWebRequest)WebRequest.Create("https://myurl.com");
        request.Method = "POST";
        System.Text.UTF8Encoding encoding = new System.Text.UTF8Encoding();
        Byte[] byteArray = encoding.GetBytes(json);
        request.ContentLength = byteArray.Length;
        request.ContentType = @"application/json";
        try
        {                
            using (var response = (HttpWebResponse)request.GetResponse())
            {
                Stream str = response.GetResponseStream();
                var sr = new StreamReader(str, encoding);                    
                
                jsonResponseToString = sr.ReadToEnd();
                var result = new OrderResult();
                result = new JavaScriptSerializer().Deserialize<OrderResult>(jsonResponseToString);
                if (str != null)
                {
                    str.Flush();
                    str.Close();
                }
            }
        }
        catch (WebException ex)
        {
            // 
        }               

The error is happening on this line:

using (var response = (HttpWebResponse)request.GetResponse())

How can I solve this, am I doing something wrong?

役に立ちましたか?

解決

As the error is trying to tell you, you need to write your bytes to the request before you can send it.

Call GetRequestStream() and write your bytes.

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top