【问题标题】:SendGrid Restful API - 400 Bad RequestSendGrid Restful API - 400 错误请求
【发布时间】:2021-09-15 12:28:37
【问题描述】:

我正在与 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();

【问题讨论】:

  • 仅供参考,有一个用于 Sendgrid github.com/sendgrid/sendgrid-csharp 的 C# 库
  • 我知道这个库是可用的,我也看过 StrongGrid 库。但在这个阶段,我不需要整个库的所有功能,我只想让基本的发送邮件功能正常工作。
  • 包含该库不会花费太多,而且它可能会让您的生活更轻松。此外,你可能有一天会需要 SendGrid 的另一个功能,谁知道呢..

标签: c# json sendgrid dotnet-httpclient sendgrid-api-v3


【解决方案1】:

起初我认为删除 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;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-04
    • 2020-11-13
    • 2011-06-18
    • 2017-02-13
    • 1970-01-01
    相关资源
    最近更新 更多