Problem:
If you submit a post request using HttpWebRequest
API without setting request body, you will receive following error message:
System.Net.WebException: 'The remote server returned an error: (411) Length Required.'
For example, If you are making post request with this code:
string requestedUrl = "http://localhost:13940/MyForm.aspx"; var request = (HttpWebRequest)WebRequest.Create(requestedUrl); request.Method = "POST"; request.ContentType = "application/x-www-form-urlencoded"; using (var resp = (HttpWebResponse)request.GetResponse()) { //do your work with response }
You will get the above error.
Solution:
-
First, if you are not sending any data in request body, then using the
GET
method instead will be a good approach.string requestedUrl = "http://localhost:13940/MyForm.aspx"; var request = (HttpWebRequest)WebRequest.Create(requestedUrl); request.Method = "GET";
-
Second thing is, somehow if you are willing to use
POST
method and you are not sending any data, then setContentLength
property of therequest
object to0
, you just have to add this line:request.ContentLength = 0;
-
Finally, if you need to post some data in the request body, then you must specify the data you are sending as well as length of the data. So the code segment will be like this:
string requestedUrl = "http://localhost:13940/MyForm.aspx"; var request = (HttpWebRequest)WebRequest.Create(requestedUrl); request.Method = "POST"; request.ContentType = "application/x-www-form-urlencoded"; //setup data to post string postData = "param1=value1¶m2=value2¶m3=value3"; ASCIIEncoding encoding = new ASCIIEncoding(); byte[] data = encoding.GetBytes(postData); //set content length request.ContentLength = data.Length; //write data to request stream var requestStream = request.GetRequestStream(); requestStream.Write(data, 0, data.Length); requestStream.Close(); using (var resp = (HttpWebResponse)request.GetResponse()) { //do your work with response }
Any of the above change would make your request successfull.