c# - 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# 代码。我已经尝试过PostAsync和PostAsJsonAsync,但没有区别。我也尝试过使用和不使用“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();
解决方案
起初,我认为删除 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;
}
推荐阅读
- ios - 如何在 iOS 中通过 CMMotionManager 获得实际加速
- python - 为什么 Stackdriver 日志中会间歇性出现空行?
- swift - 无法将 DatePicker 绑定到我的 EnvironmentObject 变量
- asp.net-mvc - ERR_RESPONSE_HEADERS_MULTIPLE_CONTENT_DISPOSITION 在配置更改后返回
- c - C : 访问冲突读取位置 0x00000044
- node.js - 如何设置自定义 Cloud Functions 路径
- r - 如何根据来自另一个 tibble 的信息添加 tibble 列
- sql - SQL Server - 从 JOIN 的一侧删除行
- java - JSON嵌套解析
- terminal - 如何方便地加载 Erlang 模块