首页 > 解决方案 > SendGrid Restful API - 400 错误请求

问题描述

我正在与 SendGrid 集成,并设法使用 Postman 让一切正常工作。但是,当从我的 C# 项目中发送请求时,我收到 400 bad request 错误消息,响应如下:

StatusCode: 400, ReasonPhrase: 'Bad Request', Version: 1.1, Content: System.Net.Http.StreamContent, Headers:
Connection: keep-alive
Access-Control-Allow-Origin: https://sendgrid.api-docs.io
Access-Control-Allow-Methods: POST
Access-Control-Allow-Headers: Authorization, Content-Type, On-behalf-of, x-sg-elas-acl
Access-Control-Max-Age: 600
X-No-CORS-Reason: https://sendgrid.com/docs/Classroom/Basics/API/cors.html
Strict-Transport-Security: max-age=600; includeSubDomains
Date: Wed, 15 Sep 2021 08:10:31 GMT
Server: nginx
Content-Length: 191
Content-Type: application/json

我检查了我的 JSON 字符串是否有效,并且架构与 SendGrid 的文档是内联的。

我不知道为什么我会收到有关 CORS 的错误消息,因为我没有使用浏览器或 JavaScript。

有人对使用 SendGrid API 的 Http 请求有任何经验吗?

下面是我发送请求的 C# 代码。我已经尝试过PostAsyncPostAsJsonAsync,但没有区别。我也尝试过使用和不使用“UserAgent”标头以及使用和不使用“Host”标头。

public static async Task<string> SendGridSendMailRequest(string json, string apiToken)
{
    string result = string.Empty;
    try
    {
        var content = new StringContent(json, Encoding.UTF8, "application/json");
                
        ProductHeaderValue header = new ProductHeaderValue("MyApp", System.Reflection.Assembly.GetExecutingAssembly().GetName().Version.ToString());
        ProductInfoHeaderValue user_agent = new ProductInfoHeaderValue(header);
        http_client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("*/*"));
        http_client.DefaultRequestHeaders.Host = "api.sendgrid.com";
        http_client.DefaultRequestHeaders.UserAgent.Add(user_agent);
        http_client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", apiToken);

        // HTTP POST
        //HttpResponseMessage response = await http_client.PostAsync("https://api.sendgrid.com/v3/mail/send", content);
        HttpResponseMessage response = await http_client.PostAsJsonAsync("https://api.sendgrid.com/v3/mail/send", content);

        // verification & response 
        if (response.IsSuccessStatusCode)
        {
           result = response.Content.ReadAsStringAsync().Result;
        }
    }
    catch (Exception ex)
    {
        MessageBox.Show(ex.ToString());
    }
    return result;
}

http_client是一个私有静态变量,如下所示:

private static HttpClient http_client = new HttpClient();

标签: c#jsonsendgriddotnet-httpclientsendgrid-api-v3

解决方案


起初,我认为删除 Authorization 标头可能是一个问题,这可能会在重定向时发生,但事实证明该问题与 TLS 有关。我应该早点考虑到这一点,因为在使用 .NET Framework 4.5 或更低版本之前,我一直被 TLS 版本问题所困扰。

这是现在可以正常工作的最终 POST 请求代码:

public static async Task<string> SendGridSendMailRequest(string json, string apiToken)
{
   string result = string.Empty;
   try
   {
      if (http_client == null)
      {
         var handler = new HttpClientHandler()
         {
            AllowAutoRedirect = false,
            SslProtocols = System.Security.Authentication.SslProtocols.Tls12 | System.Security.Authentication.SslProtocols.Tls11 | System.Security.Authentication.SslProtocols.Tls
         };
         http_client = new HttpClient(handler);
      }
      var content = new StringContent(json, Encoding.UTF8, "application/json");      
      http_client.BaseAddress = new Uri("https://api.sendgrid.com");
      http_client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("*/*"));
      http_client.DefaultRequestHeaders.Host = "api.sendgrid.com";
      http_client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", apiToken);
      HttpResponseMessage response = await http_client.PostAsync("/v3/mail/send", content);
      if (response.IsSuccessStatusCode)
      {
          result = response.Content.ReadAsStringAsync().Result;
      }
   }
   catch (Exception ex)
   {
      MessageBox.Show(ex.ToString());
   }
   return result;
}

推荐阅读