You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用C#调用MailGun API提交投诉列表遇400错误:缺失address参数

排查MailGun批量提交投诉列表400错误问题

调用MailGun API批量提交投诉列表时,返回400 Bad Request,响应提示:

"StatusCode: 400, ReasonPhrase: 'Bad Request'"
{"message":"Missing mandatory parameter: address"}

使用的C#代码如下:

public async Task Main()
{
    var serviceCo = new ServiceCollection();
    ConfigServices(serviceCo);
    var services = serviceCo.BuildServiceProvider();
    var httpClientFactory = services.GetRequiredService<IHttpClientFactory>();

    var client = httpClientFactory.CreateClient();
    var base64String = Convert.ToBase64String(Encoding.ASCII.GetBytes("api:MyApiKey"));
    client.DefaultRequestHeaders.Add("Authorization", "Basic " + base64String);
    var DomainId = "MyDomain";

    JArray json = JArray.Parse("[{'address': 'alice@example.com','createdat': ''},{'address': 'bob@example.com','createdat': ''}]");

    var postData = new StringContent(json.ToString(), Encoding.UTF8, "application/json");

    var request = await client.PostAsync("https://api.eu.mailgun.net/v3/" + DomainId + "/complaints", postData);

    var response = await request.Content.ReadAsStringAsync();

    Console.WriteLine(response);
}

问题原因

核心问题是手动编写的JSON字符串使用了单引号,而JSON规范强制要求键名和字符串值必须使用双引号。MailGun的API解析非标准JSON时,无法识别address字段,因此抛出"缺少必填参数address"的错误。

另外,空的createdat字段虽非必填,但建议要么移除该字段,要么设置为合法的ISO时间格式(如"2024-05-20T12:00:00Z"),避免额外解析异常。

修复方案

方案1:修正JSON字符串的引号

将单引号替换为双引号,确保符合JSON标准:

JArray json = JArray.Parse("[{\"address\": \"alice@example.com\",\"createdat\": \"2024-05-20T12:00:00Z\"},{\"address\": \"bob@example.com\",\"createdat\": \"2024-05-20T12:00:00Z\"}]");

方案2:用对象构建JArray(推荐)

避免手动拼接JSON字符串,直接用匿名对象构建JArray,从根源减少格式错误:

var complaints = new[]
{
    new { address = "alice@example.com", createdat = "2024-05-20T12:00:00Z" },
    new { address = "bob@example.com", createdat = "2024-05-20T12:00:00Z" }
};
JArray json = JArray.FromObject(complaints);

额外验证

确认StringContent的Content-Type已正确设置为application/json(代码中已配置,无需修改),确保API能正确识别请求体格式。

内容的提问来源于stack exchange,提问作者JDraz

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.26 23:35:17