title: Sending an Async Post WebRequest, I get a (411) Length Required
body: <p>I am using the code below to post to a web site but I get a 411 error, (
  <em><code>The remote server returned an error: (411) Length Required</code>)</em>.</p>
  
  <p>This is the function I am using, I just removed the exception handling. I get a <code>WebException</code> been thrown.</p>
  
  <pre><code>private static async Task&lt;string&gt; PostAsync(string url, string queryString, Dictionary&lt;string, string&gt; headers)
  {
    var webRequest = (HttpWebRequest)WebRequest.Create(url);
    webRequest.ContentType = "application/x-www-form-urlencoded";
    webRequest.Method = "POST";
    if (headers != null)
    {
      foreach (var header in headers)
      {
        webRequest.Headers.Add(header.Key, header.Value);
      }
    }
  
    if (!string.IsNullOrEmpty(queryString))
    {
      queryString = BuildQueryString(query);
      using (var writer = new StreamWriter(webRequest.GetRequestStream()))
      {
        writer.Write(queryString);
      }
    }
  
    //Make the request
    try
    {
      using (
        var webResponse = await Task&lt;WebResponse&gt;.Factory.FromAsync(webRequest.BeginGetResponse, webRequest.EndGetResponse, webRequest).ConfigureAwait(false))
      {
        using (var str = webResponse.GetResponseStream())
        {
          if (str != null)
          {
            using (var sr = new StreamReader(str))
            {
              return sr.ReadToEnd();
            }
          }
          return null;
        }
      }
    }
    catch (WebException wex)
    {
      // handle webexception
    }
    catch (Exception ex)
    {
      // handle webexception
    }
  }
  </code></pre>
  
  <p>I saw on some site that adding </p>
  
  <pre><code>webRequest.ContentLength = 0;
  </code></pre>
  
  <p>Would work, but in some cases I get errors that the length is wrong, (so it must be something other than 0).</p>
  
  <p>So my questions are, how do I set the content length properly?</p>
  
  <p>And, am I sending my <code>post</code> requests properly? Is there another way?</p>
  
  <p>Not sure if it matters, but I am using .NET 4.6, (but I can use 4.6.1 if needed).</p>