如果要在webrequest上等待响应,如何获取?

时间:2019-02-19 02:59:43

标签: c# web-services soap httpwebrequest iasyncresult

我正在将Windows应用程序与电子钱包商家网关集成在一起。在某些钱包上,需要先输入密码才能查看代码栏和QR码。等待从用户电话获取条形码不是问题。

但是,我有点处理混乱的情况。何时,要求密码通过网络请求在通过响应之前正在电话上进行交易。

private static async Task<string> SOAPManual(string url, string action, string xmlEnvelope)
{
    try
    {
        XmlDocument soapEnvelopeXml = CreateSoapEnvelope(xmlEnvelope);
        LogEvents($"Creating soap envelope.", EventLogEntryType.Information);
        ServicePointManager.SecurityProtocol = SecurityProtocolType.Ssl3 | SecurityProtocolType.Tls | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12;
        LogEvents($"Set security protocol.", EventLogEntryType.Information);

        HttpWebRequest webRequest = CreateWebRequest(url, action, xmlEnvelope);
        LogEvents($"Creating web request.", EventLogEntryType.Information);

        InsertSoapEnvelopeIntoWebRequest(soapEnvelopeXml, webRequest);
        LogEvents($"Inserting envelope to web request.", EventLogEntryType.Information);

        IAsyncResult asyncResult = webRequest.BeginGetResponse(null, null);
        // TRY 1:
        //while (asyncResult.IsCompleted != true)
        //{
        //    OnHTTPSPosting?.Invoke("Validate pin on wallet application to proceed.");

        //}

        // TRY 2:
        //int delaytime = 0;
        //while (true)
        //{
        //    if (asyncResult.AsyncWaitHandle.WaitOne(0))
        //    {
        //        break;
        //    }
        //    await Task.Delay(500);
        //    delaytime += 500;
        //    if (delaytime > 5000)
        //    {
        //        OnHTTPSPosting?.Invoke("Validate pin on wallet application to proceed.");
        //    }
        //}
        asyncResult.AsyncWaitHandle.WaitOne();

        LogEvents($"Web request responding.", EventLogEntryType.Information);

        string soapResult;
        using (WebResponse webResponse = webRequest.EndGetResponse(asyncResult))
        {
            LogEvents($"Retrieve web response.", EventLogEntryType.Information);

            using (StreamReader rd = new StreamReader(webResponse.GetResponseStream()))
            {
                soapResult = rd.ReadToEnd();
            }
            return FormatStringToXML(soapResult);
        }
    }
    catch (Exception ex)
    {
        LogEvents($"Error conduct SOAP request. Ex-{ex.Message}", EventLogEntryType.Error);
        OnHTTPSPosting?.Invoke("Unable to validate payment with merchant. ");
    }
    return string.Empty;
}

我尝试了2种方法,但实际上它处于挂起/挂起/等待状态(如果我的说法不正确,请纠正我)

IAsyncResult asyncResult = webRequest.BeginGetResponse(null, null);

,直到在Web服务上完全完成处理之后,它才执行代码。

我应该在代码中添加些什么以得知异步请求当前正在等待,以便我可以在屏幕上调用通知以通知用户验证其手机上的付款密码?

0 个答案:

没有答案