【发布时间】:2015-05-19 13:24:28
【问题描述】:
我是 C# 新手,我正在尝试转换我在 Chargify (https://docs.chargify.com/api-introduction) 中创建订阅的 PHP 脚本。下面是我正在使用的代码。出于测试目的,我对 JSON 字符串进行了硬编码。在解决了一天的小问题和错误之后,我终于得到了返回 422 错误的地步,但我终其一生都无法弄清楚是什么原因造成的。我已经阅读了有关 JSON 和 C# 的 Stack Overflow 上的几篇文章,但没有任何帮助。希望有更多经验的人可以看到这一点并指出我缺少的东西。非常感谢您对此事的任何见解。
[HttpPost]
public ActionResult Register(SignupViewModel regInfo)
{
string user = "xxxxxxxxxxxx";
string password = "x";
string jsonData = "{\"subscription\":{\"product_handle\":\"149-package\", \"coupon_code\" : \"\", \"customer_attributes\":{\"first_name\":\"Jerry\",\"last_name\":\"Jenkins\",\"email\":\"joe@example.com\"},\"credit_card_attributes\":{\"full_number\":\"1\",\"expiration_month\":\"10\",\"expiration_year\":\"2020\"}, \"components\" : [{\"component_id\" : 80012, \"enabled\" : false}, {\"component_id\" : 80014, \"enabled\" : true}]}}";
var httpWebRequest = (HttpWebRequest)WebRequest.Create("https://o-asandbox.chargify.com/subscriptions.json");
var encodedStr = Convert.ToBase64String(Encoding.Default.GetBytes(string.Format("{0}:{1}", user, password)));
var authorizationKey = "Basic" + " " + encodedStr; // Note: Basic case sensitive
httpWebRequest.Headers.Add("Authorization", authorizationKey);
httpWebRequest.Method = "POST";
httpWebRequest.ContentType = "Content-Type: application/json";
byte[] byteArray = Encoding.UTF8.GetBytes(jsonData);
httpWebRequest.ContentLength = byteArray.Length;
Stream dataStream = httpWebRequest.GetRequestStream();
dataStream.Write(byteArray, 0, byteArray.Length);
dataStream.Close();
var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
return View();
}
【问题讨论】:
-
请阅读文档,上面写着
422 Unprocessable Entity is returned when the charge could not be created,错误详情是Memo: cannot be blank. Amount: is not a number. Amount: must be greater than or equal to 0. This subscription is not eligible to accept charges. [Gateway response if a gateway fail] ([Your original memo]) -
问题是我不知道如何阅读错误消息的正文,直到经过更多的挖掘。我已经抓住了它,看起来我的 JSON 没有被发送,因为错误说需要产品并且需要客户。我对 Stream 做错了什么,导致它无法被发送吗?