Tag Archives: MemoryStream

Where did my request body data go?

Problem

The solution had several API controllers (see image above) that expected data to be posted in the body. Then for no reason the body data was null, and therefore the controller started throwing argument null exceptions, and the front end of course stopped working.

The issue was caused by a new custom HttpRequestProcessor (see image below), which was called in the httpRequestBegin pipeline.

private void ProcessApi(HttpRequestArgs args)
{
      using (var mem = new MemoryStream())
      {                
           HttpContext.Current.Request.InputStream.CopyTo(mem);
           HttpContext.Current.Request.InputStream.Seek(0, SeekOrigin.Begin);
                
           using (var reader = new StreamReader(mem))
           {
                mem.Seek(0, SeekOrigin.Begin);
                var body = reader.ReadToEnd();

                if (string.IsNullOrEmpty(body))
                    return;

                var requestBody = JsonConvert.DeserializeObject<RequestBody>(body);
                _setLanguageService.SetLanguage(requestBody);
           }
      }            
 }

It needed the data from the request body, for some reason the setting the position back to 0, did not work?

Therefore the controller got null instead of the data contained in the body.

Solution

Therefore it was necessary to copy the stream contents into a memory stream, read the data from that stream, then deserialize the class. See the solution below.

I hope this helps, and this issue was found Sitecore 8, with a lot of customization, patches, code and modifications over the past 16 years.