HttpWebReqest headers not sent depending on order when RequestStream was populated

101 views Asked by At

I'm writing .net 2 code and forced using it's tools. What I'm,trying to do is to send a PUT and attach headers (i.e. User-Agent). My code:

void Main()
{
    var req = (HttpWebRequest)WebRequest.Create("http://requestb.in/xan9icxa");
    req.Method = "PUT";
    req.ContentType = "application/json";
    // FillRequestBody("{'c':'d'}", req);
    req.UserAgent = "LinqPad/4";
    FillRequestBody("{'a':'b'}", req);
    var resp = (HttpWebResponse) req.GetResponse();
    //resp.Dump();
}

private static void FillRequestBody(string contentAsString, WebRequest request)
{
  var dataBytes = Encoding.UTF8.GetBytes(contentAsString);
  request.ContentLength = dataBytes.Length;
  using (var requestStream = request.GetRequestStream())
      requestStream.Write(dataBytes, 0, dataBytes.Length);
}

That runs fine and I'm getting headers as expected:

User-Agent: LinqPad/4
Content-Length: 9
Connection: close
Content-Type: application/json

But when I run FillRequestBody("{'c':'d'}", req); instead of FillRequestBody("{'a':'b'}", req); (which i tried initially and spent time trying to figure out why) - User Agent is not sent:

Content-Type: application/json
Connection: close
Content-Length: 9

The difference is the order of the call when I'm filling the request stream with data: before setting user-agent header after it.

My question is why is this happening - is there some documentation that says that filling a body of request has to be the last thing before sending http message?

0

There are 0 answers