fix(wechat): 创建二维码 POST 改用 StringContent 避免微信 412

PostAsJsonAsync 可能走 chunked 传输缺少 Content-Length,微信网关直接返回 HTTP 412 空响应。

Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
zzh 2026-07-02 11:49:12 +08:00
parent 8ef9a43f76
commit 7257bf869e

View File

@ -1,3 +1,4 @@
using System.Text;
using System.Text.Json;
using System.Text.Json.Serialization;
using System.Xml.Linq;
@ -71,9 +72,12 @@ internal sealed class WeChatMpApiClient(
}
};
using var response = await client.PostAsJsonAsync(
// 微信服务端要求 POST 带 Content-Length;PostAsJsonAsync 可能走 chunked 导致 HTTP 412
var json = JsonSerializer.Serialize(payload);
using var content = new StringContent(json, Encoding.UTF8, "application/json");
using var response = await client.PostAsync(
$"https://api.weixin.qq.com/cgi-bin/qrcode/create?access_token={Uri.EscapeDataString(accessToken)}",
payload,
content,
cancellationToken);
var result = await ReadWeChatJsonAsync<WeChatQrTicketResponse>(
@ -206,8 +210,11 @@ internal sealed class WeChatMpApiClient(
action,
(int)response.StatusCode,
raw);
var hint = response.StatusCode == System.Net.HttpStatusCode.PreconditionFailed
? "(常见于 POST 未带 Content-Length 或出口 IP 未加白名单,请检查服务端 HttpClient 与公众号 IP 白名单)"
: string.Empty;
throw new InvalidOperationException(
$"微信{action}失败 HTTP {(int)response.StatusCode} {response.ReasonPhrase}: {raw}");
$"微信{action}失败 HTTP {(int)response.StatusCode} {response.ReasonPhrase}: {raw}{hint}");
}
if (string.IsNullOrWhiteSpace(raw))