我是C#新手,我正在尝试转换我在Chargify (https://docs.chargify.com/api-introduction)中创建订阅的PHP脚本。下面是我使用的代码。出于测试目的,我硬编码了JSON字符串。经过一天的纠结和错误,我终于得到了一个422错误,但我无法找出是什么导致它。我在Stack Overflow上读过几篇关于JSON和C#的文章,但都没有帮助。希望有更多经验的人能看到这一点,并指出我遗漏的东西。提前感谢您对这件事的任何见解。
[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();
}发布于 2015-05-20 16:03:11
您的代码对于发送JSON是正确的。错误代码422是因为不可处理的数据。
在他们的文档https://docs.chargify.com/api-charges中搜索'422‘,他们说除了错误代码,还有一个JSON格式的错误响应,如下所示:
{"errors":[
"Memo: cannot be blank.",
"Amount: is not a number."
]}纠正提及的结束错误,你应该会很好。
https://stackoverflow.com/questions/30326940
复制相似问题