首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >SendGrid RESTfulAPI-400BAD请求

SendGrid RESTfulAPI-400BAD请求
EN

Stack Overflow用户
提问于 2021-09-15 12:28:37
回答 1查看 1.1K关注 0票数 0

我正致力于与SendGrid的集成,并设法让所有的一切工作正常使用邮递员。但是,当从我的C#项目中发送请求时,我收到了一个400错误的请求错误消息,它的响应如下:

代码语言:javascript
复制
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#代码。我已经尝试过PostAsJsonAsyncPostAsync,但是没有什么不同。我还尝试了与'UserAgent‘头和没有’主机‘头也有和不。

代码语言:javascript
复制
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是一个私有静态变量,如下所示:

代码语言:javascript
复制
private static HttpClient http_client = new HttpClient();
EN

回答 1

Stack Overflow用户

发布于 2021-09-15 14:59:48

起初,我想这可能是一个问题,删除授权头,这可能发生在重定向,但问题原来是有关的TLS。当我使用.NET Framework4.5或更低版本时,我应该更早地想到这一点,因为在使用TLS版本之前,我已经被TLS版本问题刺痛了。

下面是现在工作正常的最后一个POST请求代码:

代码语言:javascript
复制
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;
}
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/69193171

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档