M
M
martensit2018-06-29 18:11:24
C++ / C#
martensit, 2018-06-29 18:11:24

What snippet can be used to send the following POST request in C#?

$ curl -D- -XPUT -H "Content-Type: text/plain" \
    -H"X-Api-Key: $APIKEY" \
    --data-binary @- \
    https://dns.api.gandi.net/api/v5/zones/93cc9312-a214-408b-a75b-9d4172984746/records \
    << EOF
www IN A 192.168.0.1
    IN A 192.168.0.2
@   IN MX 10 spool.mail.gandi.net.
EOF

Through curl it looks like this.
I need to send the same, only by means of C#.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Alexey Nemiro, 2018-06-29
@martensit

using System.Net.Http;
using System.Text;

using (var client = new HttpClient())
{
  var url = "https://dns.api.gandi.net/api/v5/zones/93cc9312-a214-408b-a75b-9d4172984746/records";

  // можно просто строку (string) сделать, как будет удобно
  var data = new StringBuilder();
  data.AppendLine("www IN A 192.168.0.1");
  data.AppendLine("    IN A 192.168.0.2");
  data.AppendLine("    IN A 192.168.0.2");
  data.AppendLine("@   IN MX 10 spool.mail.gandi.net.");

  using (var content = new StringContent(data.ToString(), Encoding.UTF8, "text/plain"))
  {
    // HttpMethod.Post, если нужен POST
    using (var request = new HttpRequestMessage(HttpMethod.Put, url))
    {
      // request.Headers.Authorization = new AuthenticationHeaderValue("", "");
      request.Headers.Add("X-Api-Key", "$APIKEY");

      request.Content = content;

      // using (var response = await client.SendAsync(request)
      using (var response = client.SendAsync(request).Result)
      {
        // выбросить исключение, если сервер вернул ошибку
        response.EnsureSuccessStatusCode();

        // var result = await response.Content.ReadAsStringAsync();
        var result = response.Content.ReadAsStringAsync().Result;
        // в result будет ответ сервера
      }
    }
  }
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question