如何忽略/跳过/处理 HttpWebResponse 错误并仍将 JSON 返回到我的代码?

S.K*_*ers 2 c# asp.net api json httpwebresponse

我正在尝试通过 C# 及其 API 设置对 Stripe 的调用。我正在使用以下代码通过帖子向他们的 API 添加新卡,并使用 JSON 响应来确定下一步

(我试图去掉所有不必要的东西)

public static string stripeAPIcall(string customerId, string parameters, string stripeApiKey) {
    using (var stripeAPI = new System.Net.WebClient())
    {
      try
      {
        // set credentials
        stripeAPI.Credentials = new System.Net.NetworkCredential(stripeApiKey, "");

        //Set Headers
        stripeAPI.Headers.Add("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; .NET CLR 1.0.3705;)");
        stripeAPI.Headers[HttpRequestHeader.ContentType] = "application/x-www-form-urlencoded";

        return stripeAPI.UploadString("https://api.stripe.com/v1/customers/" + customerId + "/cards, parameters);
    }
    catch (WebException ex)
    {   
        return "error";
    }
  }
}
Run Code Online (Sandbox Code Playgroud)

当成功时,这可以很好地创建卡片。但是,如果出现错误,例如

我使用了条纹“card_declined”测试卡号 4000000000000002

结果是具有以下 JSON 结构的 402 错误

{
  "error": {
    "message": "Your card was declined.",
    "type": "card_error",
    "code": "card_declined"
  }
}
Run Code Online (Sandbox Code Playgroud)

由于 402 错误返回,这会炸毁我的 C# 代码

System.Net.WebException:远程服务器返回错误:(402) Payment Required。在 System.Net.WebClient.UploadDataInternal(Uri address, String method, Byte[] data, WebRequest& request) at System.Net.WebClient.UploadString(Uri address, String method, String data) at System.Net.WebClient.UploadString( String address, String data) at ASP.StripeGlobalHelpers.stripeAPIcall(String url, String parameters, String stripeApiKey, Boolean post)

那么,如何忽略/跳过/处理 402 错误并仍将 JSON 返回到我的应用程序?我希望能够告诉用户“您的卡被拒绝”或我可能从 Stripe 获得的任何其他错误消息。

如果您需要更多信息,请告诉我。

Mik*_*ala 5

您可以使用以下异常处理程序

catch (WebException ex)
{
    var response = ex.Response.GetResponseStream();
    return response == null ? null : new StreamReader(response).ReadToEnd();
}
Run Code Online (Sandbox Code Playgroud)

这将返回例如

{
  "error": {
    "type": "invalid_request_error",
    "message": "Invalid API Key provided: ftw?!1"
  }
}
Run Code Online (Sandbox Code Playgroud)

  • 很棒的米科!:) 效果很好。非常感谢。 (2认同)