【发布时间】: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# 代码。我已经尝试过 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();
【问题讨论】:
-
仅供参考,有一个用于 Sendgrid github.com/sendgrid/sendgrid-csharp 的 C# 库
-
我知道这个库是可用的,我也看过 StrongGrid 库。但在这个阶段,我不需要整个库的所有功能,我只想让基本的发送邮件功能正常工作。
-
包含该库不会花费太多,而且它可能会让您的生活更轻松。此外,你可能有一天会需要 SendGrid 的另一个功能,谁知道呢..
标签: c# json sendgrid dotnet-httpclient sendgrid-api-v3