HttpWebRequest and the Expect: 100-continue Header Problem
HttpWebRequest and the Expect: 100-continue Header Problem
Today I had an irritating problem when using the HttpWebRequest to POST form data over Proxy-Auth using HTTP 1.1.
When sending this request over SSL every thing was fine, but when I used POST I got this error - X-Squid-Error: ERR_INVALID_REQ 0 from the server.
After sniffing each request and drill down to understand the problem I found that not all web servers handle HTTP header "Expect: 100-Continue" correctly.
Who Add this Header? No me!
According to the HTTP 1.1 protocol, when this header is sent, the form data is not sent with the initial request.
Instead, this header is sent to the web server which responds with 100 (Continue).
Another drill down and I saw that method MakeRequest() inside System.Net.HttpWebRequest class contains the following code:
if (this._ExpectContinue && ((this._HttpWriteMode == HttpWriteMode.Chunked) || (this._ContentLength > ((long)0))))
{
this._HttpRequestHeaders.AddInternal("Expect", "100-continue");
}
So even if I wanted to remove this header from the request header collection I CAN’T.
Getting back to HTTP 1.0 is not possible, and there is no method I can override.
Finally I’ve found - ServicePoint.Expect100Continue Property
When this property is set to true, client requests that use the POST method expect to receive a 100-Continue response from the server to indicate that the client should send the data to be posted. This mechanism allows clients to avoid sending large amounts of data over the network when the server, based on the request headers, intends to reject the request.
So just change Expect100Continue to false and back to work.
request.ServicePoint.Expect100Continue = false;
Hope I can help and save you time.