REstful POST : Bytes to be written to the stream exceed the Content Length bytes size specified

This error gets thrown

Bytes to be written to the stream exceed 
the Content-Length bytes size specified. 

when I run the following code:

var request = (HttpWebRequest)WebRequest.Create(url);
request.Method = "POST";
request.ContentType = "application/json";
request.ContentLength = Encoding.UTF8.GetByteCount(json);
using (var webStream = request.GetRequestStream())
using (var requestWriter = new StreamWriter(webStream, System.Text.Encoding.UTF8))
{
    requestWriter.Write(json);
}

I read, that error could occurs when Method was HEAD or GET, but here it's POST.

Any idea what's wrong there?

Jon Skeet
people
quotationmark

The problem is that you're writing the UTF-8 BOM first, because Encoding.UTF8 does that by default. Short but complete example:

using System;
using System.IO;
using System.Text;

class Test
{
    static void Main()
    {
        string text = "text";
        var encoding = Encoding.UTF8;
        Console.WriteLine(encoding.GetByteCount(text));
        using (var stream = new MemoryStream())
        {
            using (var writer = new StreamWriter(stream, encoding))
            {
                writer.Write(text);
            }
            Console.WriteLine(BitConverter.ToString(stream.ToArray()));
        }
    }
}

Output:

4
EF-BB-BF-74-65-78-74

The simplest fix is either to add the preamble size to the content length, or to use an encoding which doesn't have a BOM:

Encoding utf8NoBom = new UTF8Encoding(false);

Use that instead of Encoding.UTF8, and all should be well.

people

See more on this question at Stackoverflow