Share via


Receiving request file or data in Streamed mode at a Web API service

By default, the mode of receiving request data at a Web API service is in Buffered mode. This is good for most scenarios, but it could be a performance problem when you expect users to upload huge files to the service. In this scenario the files would be first buffered and then you would start working on it. Since this is not ideal, in this short post I show how to enable Streamed mode of receiving data at the Web API service.

Currently the approach for enabling buffered/streamed mode of receiving data is different between SelfHost and WebHost scenarios and also the capabilities are also different.

There is a service called IHostBufferPolicySelector on HttpConfiguration, which as the name indicates is for the purpose of tuning your requests to be enable buffered/streamed mode. Currently there is only one implementation of it called WebHostBufferPolicySelector which as its name indicates is only for Web Host scenarios.

Web Host

 public class CustomWebHostBufferPolicySelector : WebHostBufferPolicySelector
     {
         // Check incoming requests and modify their buffer policy
         public override bool UseBufferedInputStream(object hostContext)
         {
             System.Web.HttpContextBase contextBase = hostContext as System.Web.HttpContextBase;
  
             if (contextBase != null
                 && contextBase.Request.ContentType != null
                 && contextBase.Request.ContentType.Contains("multipart"))
             {
                 // we are enabling streamed mode here
                 return false;
             }
  
             // let the default behavior(buffered mode) to handle the scenario
             return base.UseBufferedInputStream(hostContext);
         }
  
         // You could also chnage the response behavior too...but for this example, we are not
         // going to do anything here...I overrode this method just to demonstrate the availability
         // of this method.
         public override bool UseBufferedOutputStream(System.Net.Http.HttpResponseMessage response)
         {
             return base.UseBufferedOutputStream(response);
         }
     }

Register this service in HttpConfiguration.

 config.Services.Replace(typeof(IHostBufferPolicySelector), new CustomWebHostBufferPolicySelector());

Self Host

No implementation of IHostBufferPolicySelector currently. However, one could enable Streamed mode in Self Host by doing the following:

 selfHostConfiguration.TransferMode = System.ServiceModel.TransferMode.StreamedRequest;

You can visit this documentation for more details about the TransferMode.

As you can see currently you have the ability of enabling streamed/buffered mode on a per-request basis in Web Host, where as in Self Host scenarios, you would need to enable it for the whole service.

Comments

  • Anonymous
    July 17, 2014
    The comment has been removed