Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I send an empty HTTP POST WebRequest object from C# to IIS?

Do I need to just slap some random garbage data in a WebRequest object to get by the HTTP status code 411 restriction on IIS?

I have an HttpPost action method in an MVC 3 app that consumes a POST request with all the relevant information passed in the querystring (no body needed).

[HttpPost] public ActionResult SignUp(string email) { ... }

It worked great from Visual Studio's built in web host, Cassini. Unfortunately, once the MVC code was live on IIS [7.5 on 2008 R2], the server is pitching back an HTTP error code when I hit it from my outside C# form app.

The remote server returned an error: (411) Length Required.

Here is the calling code:

WebRequest request = WebRequest.Create("http://somewhere.com/signup/[email protected]");
request.Method = "POST";
using (WebResponse response = request.GetResponse())
using (Stream responseStream = response.GetResponseStream())
using (StreamReader responseReader = new StreamReader(responseStream)) {
    // Do something with responseReader.ReadToEnd();
}
like image 830
patridge Avatar asked May 06 '11 17:05

patridge


2 Answers

Turns out you can get this to go through by simply slapping an empty content length on the request before you send it.

WebRequest request = WebRequest.Create("http://somewhere.com/signup/[email protected]");
request.Method = "POST";
request.ContentLength = 0;

Not sure how explicitly giving an empty length vs. implying one makes a difference, but IIS was happy after I did. There are probably other ways around this, but this seems simple enough.

like image 155
patridge Avatar answered Nov 16 '22 01:11

patridge


I believe you are required to set a Content-Length header anytime you post a request to a web server:

http://msdn.microsoft.com/en-us/library/system.web.httprequest.contentlength.aspx

You could try a GET request to test it.

like image 21
maniak1982 Avatar answered Nov 16 '22 02:11

maniak1982