title: C# how to consume rest web service
body: <p>I am having a problem when I try using a rest web service in C#.</p>
  
  <p>When I try via Fiddler it works Ok.
  When I try via HTML/Ajax, it works Ok, as well.</p>
  
  <p>When I try via C# (Console Application) I get an error. </p>
  
  <p>This image is captured in fiddler. It is what I get when I try via ajax
  <a href="https://i.stack.imgur.com/7jsJ7.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/7jsJ7.png" alt="enter image description here"></a></p>
  
  <p>this image is also captured in fiddler. It is what I get when I try via C#
  <a href="https://i.stack.imgur.com/qwtky.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/qwtky.png" alt="enter image description here"></a></p>
  
  <p>As you can see, the JSON field is empty.</p>
  
  <p>This is my C# code</p>
  
  <pre><code>            string json = JsonConvert.SerializeObject(abc);
  
          HttpClient client = new HttpClient();
          client.BaseAddress = new Uri("MyURL");  //==&gt; I am filling it correctly
          client.DefaultRequestHeaders.Accept.Add(
             new MediaTypeWithQualityHeaderValue("application/json"));
  
          var response = client.PostAsJsonAsync("MyMethod", json).Result; //==&gt; I am filling my method correctly
  </code></pre>
  
  <p>But I have tried several others and always getting the same problem. (the code bellow is another one I tried) </p>
  
  <pre><code>var requisicaoWeb = WebRequest.CreateHttp("MyURL");
          requisicaoWeb.Method = "POST";
          requisicaoWeb.ContentType = "application/json";
          requisicaoWeb.ContentLength = dados.Length;
          requisicaoWeb.UserAgent = "Console app";
          requisicaoWeb.Accept = "Accept:application/json,text/javascript,*/*;q=0.01";
  
  
          //precisamos escrever os dados post para o stream
          using (var stream = requisicaoWeb.GetRequestStream())
          {
              stream.Write(MyJson, 0, dados.Length);
              stream.Close();
          }
          //ler e exibir a resposta
          using (var resposta = requisicaoWeb.GetResponse())
          {
              var streamDados = resposta.GetResponseStream();
              StreamReader reader = new StreamReader(streamDados);
              object objResponse = reader.ReadToEnd();
              var post = objResponse.ToString();//JsonConvert.DeserializeObject&lt;Post&gt;(objResponse.ToString());
              streamDados.Close();
              resposta.Close();
          }
  </code></pre>
  
  <p>Everything I try in C#, the JSON field on Fiddler is always empty and the "syntax View" description is always "Request Invalid".</p>