如何对api(http)进行异步调用。在c#中。在任务

时间:2017-03-04 11:17:23

标签: async-await task botframework

我正在使用microsoftbotframmwok开发一个聊天机器人,我有一些要求从我的任务调用api(httpclient)。但它不起作用。当我从侧面主要方法中的独立控制台应用程序测试api时,它可以工作。但在我的应用程序中,它不起作用。

我尝试从没有任务的简单方法调用api但是当它使得它基本上停止或卡在某处时,我将我的函数转换为任务并且在进行api调用时我使用await关键字来异步调用它但是它返回错误,而读取它不是结果。

这是我的代码,它进行了api调用

private async Task<String> getProblem(IDialogContext context)
{
            var response = "Thannks for contacting..";

       //here some code logix..


            SnowApiClient client = new SnowApiClient(Url, UserId, ApiPassword);
            IncidentRequestPayload payload = new IncidentRequestPayload();
            payload.caller_id = "tet111";
            payload.assignment_group = "it";
            payload.category = "complaint";
            payload.u_feedback_type = "Praise";
            payload.service_offering = "Application Management";
            payload.priority = 2;
            payload.short_description = "computer battery is dead";
            payload.comments = String.Empty;

           ApiResponse objResponse = await client.CreateIncident(payload);
       //objResponse.payload.number;
           return response;
}

//code for CreateIncident...in Api project librarary

     public async Task<ApiResponse> CreateIncident(IncidentRequestPayload payload)
            {
                var incidentRequest = new ApiRequest { method = CreateIncidentMethod, payload = payload };
                var createResult = await ExecuteRequest(incidentRequest);
                return await ReadIncident(createResult.payload.incNumber);
            }

public async Task<ApiResponse> ReadIncident(string number)
        {
            var incidentRequest = new ApiRequest { method = ReadIncidentMethod, payload = new RequestPayload { number = number } };
            return await ExecuteRequest(incidentRequest);
        }

private async Task<ApiResponse> ExecuteRequest(ApiRequest requestObject)
        {
            HttpResponseMessage response = await _client.PostAsJsonAsync("/SRintegratedAPI.rest", requestObject);

            ApiResponse responseObject = null;

            if (response.IsSuccessStatusCode)
            {
                responseObject = await response.Content.ReadAsAsync<ApiResponse>();
            }
            else
            {
                throw new System.Net.WebException(response.ReasonPhrase);
            }

            if (responseObject.result != "ok")
            {
                throw new System.Net.WebException(responseObject.message);
            }

            return responseObject;
        }

我不明白我在getProblem函数的basicalaly中如何以及在哪里使用async / await。 请帮忙

0 个答案:

没有答案