Как исправить задержку, возникающую во время связи httwebrequest и httpwebresponse в C# ?
Я хочу исправить задержку, возникающую во время связи httwebrequest и httpwebresponse в c# . Я использую службу windows .Я использую Soap UI и его вызовы API веб-службы. Я получаю задержку почти в 30 секунд при выполнении отправки на основной сервер. Я делаю связь через сервер TLS 1.2. Следовательно, при выполнении основных транзакций для больших записей происходит огромная задержка.
Что я уже пробовал:
Мой код выглядит следующим образом:
public bool CORE_FT_Posting(ref CORE_Transaction_Queue objCORE_Transaction_Queue, ref string Response) { string result = string.Empty; bool isPostSuccess = false; string Request = objCORE_Transaction_Queue.RequestXML; string PostingType = objCORE_Transaction_Queue.COREPostingType; string FileID = objCORE_Transaction_Queue.InternalFileID; string FundTransferUrl = Common.FundTransferURL; try { //LogCORE("CorePosting Started - FT T24 for Posting Type : " + PostingType + " for FileID : " + FileID + "for CB Message Type: " + objCORE_Transaction_Queue.CBMessageType, 4); LogCORE("CorePosting Started", 4); CertificateOverride oCertOverride = new CertificateOverride(); ServicePointManager.ServerCertificateValidationCallback = oCertOverride.RemoteCertificateValidationCallback; //ServicePointManager.Expect100Continue = false ; //ServicePointManager.SecurityProtocol = SecurityProtocolType.Ssl3; //const SslProtocols _Tls12 = (SslProtocols)0x00000C00; //const SecurityProtocolType Tls12 = (SecurityProtocolType)_Tls12; //ServicePointManager.SecurityProtocol = Tls12; //Added by Alex on 19.8.2020 for setting as in Client level code Start ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12 | SecurityProtocolType.Ssl3; ServicePointManager.UseNagleAlgorithm = false; ServicePointManager.Expect100Continue = false; ServicePointManager.CheckCertificateRevocationList = false; ServicePointManager.DefaultConnectionLimit = 4; //Added by Alex on 19.8.2020 for setting as in Client level code End //LogCORE("Creating HttpWebRequest Request headers started - FT T24 for Posting Type : " + PostingType + " for FileID : " + FileID + "for CB Message Type: " + objCORE_Transaction_Queue.CBMessageType, 4); LogCORE("Creating HttpWebRequest Request headers started-- ", 4); HttpWebRequest request = (HttpWebRequest)WebRequest.Create(FundTransferUrl); request.Headers.Add("SOAPAction", "https://soa.nbf.ae/T24Service/SendToT24"); request.ContentType = "text/xml; charset=\"utf-8\""; request.Accept = "gzip,deflate"; request.Method = "POST"; // request.Proxy = new WebProxy(); request.Proxy = System.Net.WebRequest.DefaultWebProxy; request.KeepAlive = false; request.ProtocolVersion = HttpVersion.Version10; //Added by Alex on 19.8.2020 for setting Response Time Out mainly for 501 FT ACC & 501 AFS FT ACC Posting as told by Client Start //if (objCORE_Transaction_Queue.CBMessageType == "501_ACC" || objCORE_Transaction_Queue.CBMessageType == "501_AFS_ACC") //{ //request.Timeout = 1000 * Convert.ToInt32(Common.HttpWebResponseTimeOut); //} //Added by Alex on 19.8.2020 for setting Response Time Out mainly for 501 FT ACC & 501 AFS FT ACC Posting as told by Client End //UnComment after Testing //Added by Alex on 19.8.2020 for configuring certiifcate addition Start if (Common.IsCerificateRequired_Posting == "1") { LogCORE("Adding Certificates - FT T24 for Posting Type : " + PostingType + " for FileID : " + FileID + "for CB Message Type: " + objCORE_Transaction_Queue.CBMessageType, 4); //UnComment after Testing (FOR TESTING) request.ClientCertificates.Add(new X509Certificate2(Common.CORE_PFXPath, Common.CORE_PFXPassword)); } //Added by Alex on 19.8.2020 for configuring certiifcate addition End //UnComment after Testing //LogCORE("Request WSS Header Creation starts - FT T24 for Posting Type : " + PostingType + " for FileID : " + FileID + "for CB Message Type: " + objCORE_Transaction_Queue.CBMessageType, 4); string Username = Common.Digest_UserName; string Password = Common.Digest_Password; string strCreatedDate = Convert.ToString(DateTime.Now); DateTime dt = new DateTime(); string strNonce; string strPssDigest; //string strCreatedDate; byte[] nonce = CreateNonce(); strNonce = Convert.ToBase64String(nonce); //CREATE DATETIME FORMAT dt = DateTime.Now; strCreatedDate = dt.ToString("yyyy-MM-ddThh:mm:ss.fffZ"); //CREATE PASSWORD DIGEST strPssDigest = CreatePasswordDigest(nonce, strCreatedDate, Password); //LogCORE("FT T24 for Posting Type : " + PostingType + " for FileID : " + FileID + " - request.Authorization : " + request.Headers + "for CB Message Type: " + objCORE_Transaction_Queue.CBMessageType, 4); LogCORE("FT T24 for Posting Type started-- request.Authorization :" + request.Headers , 4); string oRequest = @"<soapenv:Envelope xmlns:soapenv=""http://schemas.xmlsoap.org/soap/envelope/"" xmlns:t24=""https://soa.nbf.ae/T24Service/""> <soapenv:Header><wsse:Security xmlns:wsse=""http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd"" xmlns:wsu=""http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd""><wsse:UsernameToken wsu:Id=""UsernameToken-DFDA939C85F8B13ADA154211040258026""><wsse:Username>" + Username + @"</wsse:Username><wsse:Password Type=""http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-username-token-profile-1.0#PasswordDigest"">" + strPssDigest + @"</wsse:Password><wsse:Nonce EncodingType=""http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-soap-message-security-1.0#Base64Binary"">" + strNonce + @"</wsse:Nonce><wsu:Created>" + strCreatedDate + @"</wsu:Created></wsse:UsernameToken></wsse:Security></soapenv:Header> <soapenv:Body>" + Request + @"</soapenv:Body> </soapenv:Envelope>"; //LogCORE("FT T24 for Posting Type : " + PostingType + " for FileID : " + FileID + "- CorePosting Request XML : " + oRequest + "for CB Message Type: " + objCORE_Transaction_Queue.CBMessageType, 4); LogCORE("FT T24 for Posting Type started with request-- "+ oRequest, 4); using (Stream stm = request.GetRequestStream()) { using (StreamWriter stmw = new StreamWriter(stm)) { stmw.Write(oRequest); stmw.Close(); //LogCORE("Request Written - FT T24 for Posting Type : " + PostingType + " for FileID : " + FileID + "for CB Message Type: " + objCORE_Transaction_Queue.CBMessageType, 4); } } try { // UnComment after Testing HttpWebResponse httpWebRes = (HttpWebResponse)request.GetResponse(); //LogCORE("Waiting for Response of FT T24 for Posting Type : " + PostingType + " for FileID : " + FileID + "for CB Message Type: " + objCORE_Transaction_Queue.CBMessageType, 4); LogCORE("Waiting for Response of FT T24 for Posting Type STrated ", 4); //UnComment after Testing using (StreamReader responseReader = new StreamReader(httpWebRes.GetResponseStream())) { //LogCORE("CorePosting xml read response started - FT T24 for Posting Type : " + PostingType + " for FileID : " + FileID + "for CB Message Type: " + objCORE_Transaction_Queue.CBMessageType, 4); LogCORE("Response Started -- ", 4); //Comment after Testing //string filename = @"D:\FT_Response.txt"; //result = File.ReadAllText(filename); //Comment after Testing //UnComment after Testing result = responseReader.ReadLine(); //result = string.Empty; //LogCORE("CorePosting read response Received 1 - FT T24 for Posting Type : " + PostingType + " for FileID : " + FileID + " with response : " + result + "for CB Message Type: " + objCORE_Transaction_Queue.CBMessageType, 4); LogCORE("CorePosting read response Received 1 - FT T24 for Posting Type Response: "+ result, 4); // UnComment after Testing Response = result; //Response = string.Empty; objCORE_Transaction_Queue.ResponseXML = Response; responseReader.Close(); isPostSuccess = true; //LogCORE("CorePosting read response Received - FT T24 for Posting Type : " + PostingType + " for FileID : " + FileID + " with response : " + Response + "for CB Message Type: " + objCORE_Transaction_Queue.CBMessageType, 4); LogCORE("Response End -- ", 4); } //UnComment after Testing } catch (WebException ex) { isPostSuccess = false; objCORE_Transaction_Queue.PostingStatus = "E"; string StatusCode = string.Empty; //Added by Alex on 31.5.2020 for logging exceptional response Start objCORE_Transaction_Queue.ResponseXML = ex.Response.ToString(); LogCORE("CorePosting Response Xml - FT T24 for Posting Type : " + PostingType + " for FileID : " + FileID + " with response : " + ex.Response +"for CB Message Type: " + objCORE_Transaction_Queue.CBMessageType, 4); //Added by Alex on 31.5.2020 for logging exceptional response End using (WebResponse response = ex.Response) { //LogCORE("CorePosting Response Xml - FT T24 for Posting Type : " + PostingType + " for FileID : " + FileID + " with response : " + ex.Response, 4); HttpWebResponse httpResponse = (HttpWebResponse)response; StatusCode = httpResponse.StatusCode.ToString(); string message = new StreamReader(ex.Response.GetResponseStream()).ReadToEnd(); LogCORE("Exception in retrieving FT T24 Response for Posting Type : " + PostingType + " for FileID : " + FileID + " with Exception : " + ex.Message + Environment.NewLine + "Custom Exception : " + message + Environment.NewLine + "Inner Exception : " + ex.InnerException + Environment.NewLine + "Stack Trace : " + ex.StackTrace + ". Status Code : " + StatusCode, 1); } } catch (Exception ex) { LogCORE("Exception in retrieving FT T24 Response for Posting Type : " + PostingType + " for FileID : " + FileID + " with Inner Exception : " + ex.InnerException + Environment.NewLine + "with Exception : " + ex.Message + Environment.NewLine + "at Stack Trace:" + ex.StackTrace, 1); isPostSuccess = false; objCORE_Transaction_Queue.PostingStatus = "E"; } } catch (Exception ex) { isPostSuccess = false; LogCORE("Main Exception in FT T24 Response for Posting Type : " + PostingType + " for FileID : " + FileID + " with Inner Exception : " + ex.InnerException + Environment.NewLine + "with Exception : " + ex.Message + Environment.NewLine + "at Stack Trace:" + ex.StackTrace, 1); objCORE_Transaction_Queue.PostingStatus = "E"; } LogCORE("CorePosting completed", 4); return isPostSuccess; }
Gerry Schmitz
Вам нужно остановить свой код, чтобы увидеть, где находится проблема. Вам нужно "сосредоточиться" вместо того, чтобы ожидать, что другие будут пробираться через эту кучу.
Richard MacCutchan
Посмотрите, что происходит на сервере, чтобы вызвать задержку. Вам действительно нужно понять, что никто здесь не может воссоздать вашу среду и протестировать ваш код, даже если бы захотел. Поэтому убедитесь, что на обоих концах есть хорошее ведение журнала, запустите код несколько раз и посмотрите, что происходит.
PIEBALDconsult
Серверы и службы требуют времени. Сетевой трафик требует времени. Аутентификация требует времени. Запросы к базе данных и тому подобное требуют времени.
Они не находятся под контролем вашего кода, и в лучшем случае вы можете улучшить сеть или улучшить аппаратное обеспечение, на котором работает служба.
Если ваш код "запрашивает" данные с сервера, то, возможно, вы можете улучшить ситуацию, изменив количество запрашиваемых данных за один раз.
Для одного такого приложения, над которым я работаю (запрашиваю корпоративную систему SPLUNK), вместо того чтобы запрашивать данные за полный день, я запрашиваю один час за раз. Это дает мне гораздо лучшую пропускную способность, а также улучшает то, насколько хорошо сервер(ы) может обслуживать другие приложения.