You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

PayPal HTTP客户端返回Void,无法获取创建计划的JSON结果

PayPal计费计划创建成功但无法获取返回JSON的问题

问题详情

调用PayPal接口创建计费计划时,沙箱环境返回状态码Created,但执行response.Result<string>()时抛出异常:

MESSAGE:
Unable to cast object of type 'System.Void' to type 'System.String'.

SOURCE:
PayPalHttp-Dotnet

原调用代码:

var client = Functions.GetPaypalClient();
using (var request = new HttpRequest("/v1/billing/plans", HttpMethod.Post))
{
    request.ContentType = "application/json";
    request.Content = new StringContent(strData);
    request.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json");

    var response = Task.Run(() => client.Execute(request)).Result;

    response.StatusCode.ToString().BasicLog();
    var data = response.Result<string>();
    data.BasicLog();
}

解决方案

问题出在Result<T>()方法的处理逻辑上:当接口返回201 Created时,部分场景下Result<T>()会因响应体处理逻辑问题触发类型转换异常。可以通过直接读取响应流的方式获取返回JSON:

修复后的代码(同步版本)

var client = Functions.GetPaypalClient();
using (var request = new HttpRequest("/v1/billing/plans", HttpMethod.Post))
{
    request.ContentType = "application/json";
    request.Content = new StringContent(strData);
    request.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json");

    var response = Task.Run(() => client.Execute(request)).Result;

    response.StatusCode.ToString().BasicLog();
    
    // 直接读取响应流内容
    string data = null;
    if (response.Content != null)
    {
        using var reader = new StreamReader(response.Content);
        data = reader.ReadToEnd();
    }
    data?.BasicLog();
}

推荐异步版本(避免线程阻塞)

// 确保所在方法标记为async
var client = Functions.GetPaypalClient();
using (var request = new HttpRequest("/v1/billing/plans", HttpMethod.Post))
{
    request.ContentType = "application/json";
    request.Content = new StringContent(strData);
    request.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json");

    var response = await client.Execute(request);

    response.StatusCode.ToString().BasicLog();
    
    string data = null;
    if (response.Content != null)
    {
        using var reader = new StreamReader(response.Content);
        data = reader.ReadToEnd();
    }
    data?.BasicLog();
}

补充说明

PayPal部分201 Created响应可能为空,但计费计划创建成功时通常会返回完整的计划JSON数据。直接读取响应流是更可靠的方式,可绕过Result<T>()方法的类型转换限制。

内容的提问来源于stack exchange,提问作者Tom Gullen

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.28 13:43:22