Paypal 通过 C# 中的 400 Bad Request 错误保存了卡余 API
Posted
技术标签:
【中文标题】Paypal 通过 C# 中的 400 Bad Request 错误保存了卡余 API【英文标题】:Paypal saved card rest API through 400 Bad Request error in C# 【发布时间】:2016-10-11 07:49:25 【问题描述】:我正在使用 .net MVC C# 开发应用程序。我试图调用 PayPal 的 rest API 来保存信用卡详细信息,我的代码工作正常,但突然从 400 Bad Request 异常开始。这是我的代码,
private static async Task<string> StorePaymentCards(string accessToken, PaymentInfoModel cardDetails)
try
var httpWebRequest = (HttpWebRequest)WebRequest.Create("https://api.sandbox.paypal.com/v1/vault/credit-card");
var result = "";
httpWebRequest.ContentType = "application/json; charset=utf-8";
httpWebRequest.Method = "POST";
httpWebRequest.Accept = "application/json; charset=utf-8";
httpWebRequest.Headers.Add("Authorization", "Bearer " + accessToken);
using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
var loginjson = new javascriptSerializer().Serialize(new
payer_id = cardDetails.PayerId.Trim(),
type = cardDetails.CardType.Trim(),
number = cardDetails.CardNumber.Trim(),
expire_month = cardDetails.ExpireMonth.Trim(),
expire_year = cardDetails.ExpireYear.Trim(),
first_name = cardDetails.FirstName.Trim()
);
streamWriter.Write(loginjson);
streamWriter.Flush();
streamWriter.Close();
//The code fails when creating the Response here, and go into catch block
var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
result = streamReader.ReadToEnd();
return result;
catch (Exception ex)
return ex.GetBaseException().Message;
谁能帮我解决这个错误? 提前谢谢你。
【问题讨论】:
调试代码并发布完整的异常消息。错误的请求可能意味着很多不同的场景。检查异常的所有属性以获取更具体的消息 @cFrozenDeath,感谢您的回复,这是我收到的例外情况。 System.Net.WebException:远程服务器返回错误:(400)错误请求。在 System.Net.HttpWebRequest.GetResponse() 信息还不够。异常(catch 块内的前对象)应该有更多的细节。 @cFrozenDeath,我弄错了,我没有输入正确的卡详细信息,因此引发了 400 异常。感谢您的及时回复。 【参考方案1】: private static async Task<string> StorePaymentCards(string accessToken, PaymentInfoModel cardDetails)
try
//my stuff
catch (WebException ex)
string text = null;
using (WebResponse response = ex.Response)
HttpWebResponse httpResponse = (HttpWebResponse)response;
Console.WriteLine("Error code: 0", httpResponse.StatusCode);
using (Stream data = response.GetResponseStream())
using (var reader = new StreamReader(data))
text = reader.ReadToEnd();
Console.WriteLine(text);
return text; //ex.GetBaseException().Message;
这是我在 catch 块中所做的更改以跟踪正确的错误,因此它返回了我所面临的错误。
【讨论】:
以上是关于Paypal 通过 C# 中的 400 Bad Request 错误保存了卡余 API的主要内容,如果未能解决你的问题,请参考以下文章
HTTPClient 返回 400 Bad Request 但 Postman 在 C# 中返回 201
PostAsJsonAsync C# - 如何为 POST 请求正确设置标头 - BAD REQUEST 400
Oauth2:远程服务器返回错误:(400) Bad Request
通过 Retrofit 调用发布请求时出现 400 bad request 错误