From 7257bf869ee199be2b4f9af6a8259bfa4676efb7 Mon Sep 17 00:00:00 2001 From: zzh <1368735060@qq.com> Date: Thu, 2 Jul 2026 11:49:12 +0800 Subject: [PATCH] =?UTF-8?q?fix(wechat):=20=E5=88=9B=E5=BB=BA=E4=BA=8C?= =?UTF-8?q?=E7=BB=B4=E7=A0=81=20POST=20=E6=94=B9=E7=94=A8=20StringContent?= =?UTF-8?q?=20=E9=81=BF=E5=85=8D=E5=BE=AE=E4=BF=A1=20412?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit PostAsJsonAsync 可能走 chunked 传输缺少 Content-Length,微信网关直接返回 HTTP 412 空响应。 Co-authored-by: Cursor --- .../WeChat/Services/WeChatMpApiClient.cs | 13 ++++++++++--- 1 file changed, 10 insertions(+), 3 deletions(-) diff --git a/src/SimpleAdmin.Api/WeChat/Services/WeChatMpApiClient.cs b/src/SimpleAdmin.Api/WeChat/Services/WeChatMpApiClient.cs index bd86575..a669c72 100644 --- a/src/SimpleAdmin.Api/WeChat/Services/WeChatMpApiClient.cs +++ b/src/SimpleAdmin.Api/WeChat/Services/WeChatMpApiClient.cs @@ -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( @@ -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))