添加更多JSON属性时SendGrid API返回400错误求助
SendGrid API创建Single Send时添加
send_at/sender_id等属性触发JSON解析错误 我在Azure Functions端点中调用SendGrid API,创建并调度发送给联系人列表的Single Send邮件。以下是能成功创建Single Send并返回200响应的最小代码:
private static SendGridClient _client = new SendGridClient( Environment.GetEnvironmentVariable("SendGridApiKey") ); ... var data = new { name = "Title", send_to = new { list_ids = new [] { $"{Environment.GetEnvironmentVariable("SendGridMailingId")}", } }, email_config = new { design_id = $"{Environment.GetEnvironmentVariable("SendGridDesignId")}", } }; var singleSendResp = await _client.RequestAsync( method: SendGridClient.Method.POST, urlPath: "marketing/singlesends", requestBody: JsonConvert.SerializeObject(data) ); return singleSendResp;
但只要添加send_at: "now"、suppression_group_id或sender_id任一属性(单独或组合添加),就会收到如下错误响应:
{ "errors": [ { "field": "", "message": "json could not be unmarshalled" } ] }
我试过这些属性的各种组合,也尝试补充了所有非必填属性(因为使用了design_id,所以未包含subject、html_content等)。当前使用的是SendGrid NuGet包9.28.1版本(对应SendGrid v3 API),本地通过Postman测试,使用免费版API。
附上理想的请求对象代码:
var data = new { name = "Title", send_at = "now", send_to = new { list_ids = new [] { Environment.GetEnvironmentVariable("SendGridMailingId") } }, email_config = new { design_id = Environment.GetEnvironmentVariable("SendGridDesignId"), sender_id = Environment.GetEnvironmentVariable("SendGridSenderId"), suppression_group_id = Environment.GetEnvironmentVariable("SendGridSuppressionId") } };
问题原因与解决方法
send_at参数格式错误:SendGrid v3 API不接受"now"作为send_at的取值,若需立即发送,直接省略该字段即可(API默认会立即发送);若需定时发送,必须传入整数类型的Unix时间戳,而非字符串。属性类型不匹配:
sender_id和suppression_group_id均为整数类型,但从环境变量获取的是字符串,直接赋值会导致JSON序列化后类型错误(字符串而非数字),触发解析失败。需将其转换为整数后再传入。
修正后的代码示例(立即发送):
var data = new { name = "Title", send_to = new { list_ids = new [] { Environment.GetEnvironmentVariable("SendGridMailingId") } }, email_config = new { design_id = Environment.GetEnvironmentVariable("SendGridDesignId"), sender_id = int.Parse(Environment.GetEnvironmentVariable("SendGridSenderId")), suppression_group_id = int.Parse(Environment.GetEnvironmentVariable("SendGridSuppressionId")) } };
定时发送示例(30分钟后):
// 计算30分钟后的Unix时间戳(整数类型) var scheduledSendTime = DateTimeOffset.UtcNow.AddMinutes(30).ToUnixTimeSeconds(); var data = new { name = "Title", send_at = scheduledSendTime, send_to = new { list_ids = new [] { Environment.GetEnvironmentVariable("SendGridMailingId") } }, email_config = new { design_id = Environment.GetEnvironmentVariable("SendGridDesignId"), sender_id = int.Parse(Environment.GetEnvironmentVariable("SendGridSenderId")), suppression_group_id = int.Parse(Environment.GetEnvironmentVariable("SendGridSuppressionId")) } };
额外验证建议
- 序列化后打印JSON内容,检查
sender_id、suppression_group_id是否为数字类型(无引号),send_at是否为整数(若添加)。 - 确认环境变量中的
SendGridSenderId和SendGridSuppressionId为有效整数,无多余空格或非数字字符。
内容的提问来源于stack exchange,提问作者Sean Poston
相关产品推荐
相关产品推荐

