HttpContext.Current.Request.InputStream property throws exception “This method or property is not supported after HttpRequest.GetBufferlessInputStream has been invoked.” or HttpContext.Current.Request.Forms parameters empty

In .net 4.5 WCF leveraged the buffer less input stream for scalability benefits. As a result when you try to access the HttpContext.Current.Request.InputStream property you may end up with the below exception, as the InputStream property tries to get you handle to the Classic stream as they both are incompatible. You may also see the other side effect of HttpContext.Current.Request.Form parameters becoming empty.

This method or property is not supported after HttpRequest.GetBufferlessInputStream has been invoked.”

If you had a WCF 4.0 app which worked perfectly but on upgrading your .net framework to 4.5 you notice the service failing on accessing this property, here is the way to work-around the issue:

  1. Add a simple HttpModule in the same WCF project which will access the InputStream property for each request before WCF reads it so that it will enforce the HttpContext.Request.ReadEntityBody to be "Classic" and will ensure compatibility. 

public class WcfReadEntityBodyModeWorkaroundModule : IHttpModule

    {

        public void Dispose()

        {  

        }

         public void Init(HttpApplication context)

        {

            context.BeginRequest += context_BeginRequest;

        }

         void context_BeginRequest(object sender, EventArgs e)

        {

            //This will force the HttpContext.Request.ReadEntityBody to be "Classic" and will ensure compatibility..

            Stream stream = (sender as HttpApplication).Request.InputStream;

        }

  }  

2. Register this module in your web.config by adding these lines in <configuration><modules> setting.

  <system.webServer>

    <modules ...>

      <!-- Register the managed module -->

      <add name="WcfReadEntityBodyModeWorkaroundModule" type="MyAssembly.WcfReadEntityBodyModeWorkaroundModule, MyAssembly" />

    </modules>

<…

If your project cannot be modified, then you can write this Http module in a separate assembly, GAC it separately and register this module in the web.config.

Now try accessing the service it should succeed for you!

 

Note: This issue has been fixed with .net 4.5.1 update. To get the old behavior (4.0 behavior) back please apply the below compat switch in your web.config:

<configuration>
<appSettings>
<add key="wcf:serviceHostingEnvironment:useClassicReadEntityBodyMode" value="true" />
</appSettings>
</configuration>