Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Supporting the "Expect: 100-continue" header with ASP.NET MVC

I'm implementing a REST API using ASP.NET MVC, and a little stumbling block has come up in the form of the Expect: 100-continue request header for requests with a post body.

RFC 2616 states that:

Upon receiving a request which includes an Expect request-header field with the "100-continue" expectation, an origin server MUST either respond with 100 (Continue) status and continue to read from the input stream, or respond with a final status code. The origin server MUST NOT wait for the request body before sending the 100 (Continue) response. If it responds with a final status code, it MAY close the transport connection or it MAY continue to read and discard the rest of the request. It MUST NOT perform the requested method if it returns a final status code.

This sounds to me like I need to make two responses to the request, i.e. it needs to immediately send a HTTP 100 Continue response, and then continue reading from the original request stream (i.e. HttpContext.Request.InputStream) without ending the request, and then finally sending the resultant status code (for the sake of argument, lets say it's a 204 No Content result).

So, questions are:

  1. Am I reading the specification right, that I need to make two responses to a request?
  2. How can this be done in ASP.NET MVC?

w.r.t. (2) I have tried using the following code before proceeding to read the input stream...

HttpContext.Response.StatusCode = 100;
HttpContext.Response.Flush();
HttpContext.Response.Clear();

...but when I try to set the final 204 status code I get the error:

System.Web.HttpException: Server cannot set status after HTTP headers have been sent.

like image 206
Greg Beech Avatar asked May 18 '09 18:05

Greg Beech


2 Answers

The .NET framework by default always sends the expect: 100-continue header for every HTTP 1.1 post. This behavior can be programmatically controlled per request via the System.Net.ServicePoint.Expect100Continue property like so:

HttpWebRequest httpReq = GetHttpWebRequestForPost();
httpReq.ServicePoint.Expect100Continue = false;

It can also be globally controlled programmatically:

System.Net.ServicePointManager.Expect100Continue = false;

...or globally through configuration:

<system.net>
  <settings>
    <servicePointManager expect100Continue="false"/>
  </settings>
</system.net>

Thank you Lance Olson and Phil Haack for this info.

like image 185
John Berberich Avatar answered Oct 19 '22 09:10

John Berberich


100-continue should be handled by IIS. Is there a reason why you want to do this explicitly?

like image 44
DSO Avatar answered Oct 19 '22 10:10

DSO