Search code examples
c#.nethttpwebrequest

C# HttpWebRequest.Write does not send content


Trying to send a web request with some body content. The important part is that I need some data in the body of the post request. My understanding of how to do this is to open a WebRequestStream, and then write the bytes to it, then to close it. This is supposed to be simple. Here is my code:

        HttpWebRequest request;
        request = (HttpWebRequest)WebRequest.Create("http://localhost:50203/api/Values");//

        request.Method = "POST";
            byte[] requestBody = ASCIIEncoding.ASCII.GetBytes(HttpUtility.UrlEncode("grant_type=client_credentials"));
            Stream requestBodyStream = request.GetRequestStream();
            requestBodyStream.Write(requestBody, 0, requestBody.Length);
            requestBodyStream.Flush();
            requestBodyStream.Close();
            WebResponse response = (HttpWebResponse)request.GetResponse();
            Stream dataStream = response.GetResponseStream();
            StreamReader reader = new StreamReader(dataStream);
            myString = reader.ReadToEnd();

But the RequestBodyStream.Write method is not sending anything in the body. I know this because I'm running the server side program at the other end.

I also tried to do this with a StreamWriter instead of using a byte stream, and I get the same result. No matter how I do it, there is no content in the body.

My understanding is that closing the stream is what sends the actual data. I also tried adding a Flush() method to the stream.

Why is this method not producing any body?


Solution

  • Add 'ContentType' and 'ContentLength' headers to the request instance:

    request.ContentType = "application/json"; // Or whatever you want
    request.ContentLength = requestBody.Length;