调用Execute方法在常规代码执行中返回Null,但在逐步执行时返回数据

时间:2019-05-13 12:07:21

标签: c# asp.net asp.net-web-api restsharp

我正在尝试使用RestSharp库调用API。运行代码通常无法获取数据,但是当我在调试时逐步执行代码时, Execute 方法将获取数据。

//execute the request
var response = client.Execute<JimiResponse<List<DeviceTrackListResponse>>>(webRequest);
private List<DeviceTrackListResponse> GetDeviceTrackListData(string accessToken, string imei, DateTime startDate, DateTime endDate)
{
    var client = new RestClient(_security.EndPoint);
    var webRequest = new RestRequest(Method.POST);

    var requiredParams = new DeviceTrackListRequest(accessToken)
    {
        app_key = _security.AppKey,
        imei = imei,
        method = "jimi.device.track.list",
        begin_time = startDate.ToUniversalTime().ToString("yyyy-MM-dd HH:mm:ss"),
        end_time = endDate.ToUniversalTime().ToString("yyyy-MM-dd HH:mm:ss")
    };

    webRequest.AddObject(requiredParams);

    try
    {
        var signature = Signature.SignTopRequest(requiredParams.GetProperties(), _security.SecurityToken, requiredParams.sign_method);
        webRequest.AddParameter("sign", signature);

        //execute the request
        var response = client.Execute<JimiResponse<List<DeviceTrackListResponse>>>(webRequest);

        var responseData = response?.Data?.Result;

        if (response.StatusCode == HttpStatusCode.OK && responseData != null)
        {
            return responseData;
        }
        else
        {
            return new List<DeviceTrackListResponse>();
        }
    }
    catch (Exception ex)
    {
        return new List<DeviceTrackListResponse>();
    }
}

1 个答案:

答案 0 :(得分:0)

您没有异步运行此代码,它不会等待响应并在到达该行后继续运行。

 private async Task<List<DeviceTrackListResponse>> GetDeviceTrackListData(string accessToken, string imei, DateTime startDate, DateTime endDate)
{
    var client = new RestClient(_security.EndPoint);
    var webRequest = new RestRequest(Method.POST);

    var requiredParams = new DeviceTrackListRequest(accessToken)
    {
        app_key = _security.AppKey,
        imei = imei,
        method = "jimi.device.track.list",
        begin_time = startDate.ToUniversalTime().ToString("yyyy-MM-dd HH:mm:ss"),
        end_time = endDate.ToUniversalTime().ToString("yyyy-MM-dd HH:mm:ss")
    };

    webRequest.AddObject(requiredParams);

    try
    {
        var signature = Signature.SignTopRequest(requiredParams.GetProperties(), _security.SecurityToken, requiredParams.sign_method);
        webRequest.AddParameter("sign", signature);

        //execute the request
        var response = await client.Execute<JimiResponse<List<DeviceTrackListResponse>>>(webRequest);

        var responseData = response?.Data;

        if (response.StatusCode == HttpStatusCode.OK && responseData != null)
        {
            return responseData;
        }
        else
        {
            return new List<DeviceTrackListResponse>();
        }
    }
    catch (Exception ex)
    {
        return new List<DeviceTrackListResponse>();
    }
}