C#向WordPress/WooCommerce的Web API提交JSON数据报错求助
问题排查与修复方案
核心问题分析
对比可正常运行的PHP代码和你的C#实现,有两个关键问题导致HTTP 500错误:
1. 重复发送POST请求
你的C#代码里连续调用了两次UploadValues:
// 多余的首次请求,会先向服务器提交一次数据 client.UploadValues(endpointUrl, "POST", postData); try { // 第二次重复发送请求 byte[] responseBytes = client.UploadValues(endpointUrl, "POST", postData); // ... }
首次请求已经触发服务器端逻辑,可能导致状态异常,进而让第二次请求返回500错误。
2. JSON字符串的潜在格式问题
如果jsonData是手动拼接的字符串,很容易出现引号未转义、格式不规范的情况,服务器解析JSON失败后会返回500错误。PHP代码里的JSON是硬编码的规范字符串,而C#如果手动拼接容易出错。
修正后的C#代码
string endpointUrl = "https://xxx.xxx/oogabooga/wp-json/custom/v1/import"; // 用序列化方式生成标准JSON,避免手动拼接出错 var productPayload = new { v = "imaverifiedupload", products = new[] { new { type = "simple", name = "Fallout: New Vegas Endpoint check", description = "Fallout: New Vegas (PS3)", sku = "093", product_category = "310", sub_category = "370", price = "2.50", manage_stock = 1, quantity = 0, image_name = "fallout_3_ps3.jpg" } } }; string jsonData = System.Text.Json.JsonSerializer.Serialize(productPayload); NameValueCollection postData = new NameValueCollection { { "json_data", jsonData }, }; using (WebClient client = new WebClient()) { ServicePointManager.Expect100Continue = true; ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12; ServicePointManager.ServerCertificateValidationCallback = delegate { return true; }; try { // 仅发送一次POST请求 byte[] responseBytes = client.UploadValues(endpointUrl, "POST", postData); string response = System.Text.Encoding.UTF8.GetString(responseBytes); Console.WriteLine(response); } catch (WebException ex) { // 捕获服务器返回的详细错误信息,方便排查 if (ex.Response is HttpWebResponse errorResponse) { using (StreamReader reader = new StreamReader(errorResponse.GetResponseStream())) { string errorDetails = reader.ReadToEnd(); Console.WriteLine("服务器错误详情: " + errorDetails); } } Console.WriteLine("WebException: " + ex.Message); } }
额外调试建议
- 查看服务器日志:打开WordPress/WooCommerce的错误日志,获取500错误的具体触发原因(比如JSON解析失败、权限不足)。
- 抓包对比请求:用Fiddler等工具对比PHP和C#发送的请求内容,确认表单参数、编码规则是否完全一致。
内容的提问来源于stack exchange,提问作者johnporter
相关产品推荐
相关产品推荐

