异步任务<dynamic>的返回结果出错

时间:2018-03-07 13:44:12

标签: c# asp.net

我正在调用API并成功获取结果。我还将结果转换为对象&#34; ResultCgOrder&#34;

问题是,当我返回结果并将其捕获到我的控制器时,它会给出错误

我的代码:

public async Task<dynamic> createOrder(CgOrder data){
        ResultCgOrder resultCgOrder = new ResultCgOrder();
        string path = "https://XXX/orders";

        ApiHeaderGet(createHashString());

        var body = new FormUrlEncodedContent(new[]{
            new KeyValuePair<string, string>("order_id", data.OrderId.ToString()),
            new KeyValuePair<string, string>("price", data.Price.ToString()),               
            new KeyValuePair<string, string>("success_url", data.SuccessUrl)
        }
            );

        var response = await client.PostAsync(path, body);

        if (response.IsSuccessStatusCode){
            resultCgOrder = await response.Content.ReadAsAsync<ResultCgOrder>();
        }

        return  resultCgOrder;
    }

现在我通过使用以下代码来调用它;

APIHelper apiCall = new APIHelper ();
ResultCgOrder resultOrder = apiCall.createOrder(CgOrder);

显示错误的最后一行 - 无法隐式转换类型&#39; System.Threading.Tasks.Task dynamic&#39; to&#39; xxx.Code.ResultCgOrder&#39; - 错误屏幕截图是here

1 个答案:

答案 0 :(得分:-1)

这就是我的工作方式:

public async Task<ResultCgOrder> createOrder(CgOrder data)
    {
        ResultCgOrder resultCgOrder = new ResultCgOrder();
        string path = "https://api-xxx";

        nonce = Convert.ToString(Stopwatch.GetTimestamp());
        ApiHeaderGet(createHashString());

        var body = new FormUrlEncodedContent(new[]{
            new KeyValuePair<string, string>("order_id", data.OrderId),
            new KeyValuePair<string, string>("price", data.Price.ToString()),               
        }
            );

        var incomingResult =  client.PostAsync(path, body).Result;
        if (incomingResult.IsSuccessStatusCode)
        {
            resultCgOrder = await incomingResult.Content.ReadAsAsync<ResultCgOrder>();
        }

        return resultCgOrder;
    }

我用以下方式调用它:

 var resultCgOrder =  apiCall.createOrder(CgOrder);               
 string newString = resultCgOrder.Result.price;