Search code examples
c#httpwebresponse

HTTPwebresponse not working, I can't get anything to POST


So I get a bad request error whenever I run this. I have looked on stack overflow but can't seem to get any of the responses from users to work. Any help would be appreciated.

//Make a request to the SendGrid API to add the email address to the globabl unsubscirbe

        HttpWebRequest request1 = (HttpWebRequest)WebRequest.Create("https://api.sendgrid.com/v3/asm/suppressions/global");
        request1.Headers.Add("authorization", "My_API_KEY");
        string Data = "{" + "recipient_emails:[" + "\"" +(txtEmail.Text) + "\"" + "]}"; //place body here
        request1.Method = "POST";
        request1.ContentType = "application/json";

        using (StreamWriter sw = new StreamWriter(request1.GetRequestStream()))
        {

            sw.Write(Data);

        }

        HttpWebResponse response1= (HttpWebResponse)request1.GetResponse();

        using (var streamReader = new StreamReader(response1.GetResponseStream()))
        {
            var result = streamReader.ReadToEnd();
            result.ToString();
        }

Solution

  • It is an excerpt.

    var apiKey = Environment.GetEnvironmentVariable("NAME_OF_THE_ENVIRONMENT_VARIABLE_FOR_YOUR_SENDGRID_KEY");
    
    var client = new SendGridClient(apiKey);
    
    string data = @"{
      'recipient_emails': [
        '[email protected]', 
        '[email protected]'
      ]
    }";
    Object json = JsonConvert.DeserializeObject<Object>(data);
    data = json.ToString();
    var response = await client.RequestAsync(method: SendGridClient.Method.POST, urlPath: "asm/suppressions/global", requestBody: data);
    Console.WriteLine(response.StatusCode);
    Console.WriteLine(response.Body.ReadAsStringAsync().Result);
    Console.WriteLine(response.Headers.ToString());
    Console.ReadLine();