System.Net.WebException: запрос не выполнен со статусом HTTP 400: неверный запрос. динамический вызов веб-сервиса

Я динамически вызываю веб-службу через свою веб-службу. Я сохранил serviceName, MethodToCall и массив параметров в своей таблице базы данных и выполнил эти два метода для вызова динамического URL-адреса службы с расширением .asmx и его метода без добавления ссылки на него в моем приложении. Это работает нормально.

Следующий код здесь.

public string ShowThirdParty(String strURL, String[] Params, String MethodToCall, String ServiceName)
        {

   String Result = String.Empty;

//Specify service Url without ?wsdl suffix.
            //Reference urls for code help
            ///http://www.codeproject.com/KB/webservices/webservice_.aspx?msg=3197985#xx3197985xx
            //http://www.codeproject.com/KB/cpp/CallWebServicesDynamic.aspx
            //String WSUrl = "http://localhost/ThirdParty/WebService.asmx";
            String WSUrl = strURL;

            //Specify service name
            String WSName = ServiceName;

            //Specify method name to be called
            String WSMethodName = MethodToCall;

            //Parameters passed to the method
            String[] WSMethodArguments = Params;
            //WSMethodArguments[0] = "20500";

            //Create and Call Service Wrapper
            Object WSResults = CallWebService(WSUrl, WSName, WSMethodName, WSMethodArguments);

            if (WSResults != null)
            {
                //Decode Results
                if (WSResults is DataSet)
                {
                    Result += ("Result: \r\n" + ((DataSet)WSResults).GetXml());
                }
                else if (WSResults is Boolean)
                {   
                   bool BooleanResult = (Boolean)WSResults;
                    if(BooleanResult)
                          Result += "Result: \r\n" + "Success";
                    else
                          Result += "Result: \r\n" + "Failure";
                }
                else if (WSResults.GetType().IsArray)
                {
                    Object[] oa = (Object[])WSResults;
                    //Retrieve a property value withour reflection...
                    PropertyDescriptor descriptor1 = TypeDescriptor.GetProperties(oa[0]).Find("locationID", true);
                    foreach (Object oae in oa)
                    {
                        Result += ("Result: " + descriptor1.GetValue(oae).ToString() + "\r\n");
                    }
                }
                else
                {
                    Result += ("Result: \r\n" + WSResults.ToString());
                }
            }
            return Result;
        }

        public Object CallWebService(string webServiceAsmxUrl,
       string serviceName, string methodName, string[] args)
        {

            try
            {
                System.Net.WebClient client = new System.Net.WebClient();
                Uri objURI = new Uri(webServiceAsmxUrl);
                //bool isProxy = client.Proxy.IsBypassed(objURI);
                //objURI = client.Proxy.GetProxy(objURI);
                //-Connect To the web service
               // System.IO.Stream stream = client.OpenRead(webServiceAsmxUrl + "?wsdl");

                string ccc = webServiceAsmxUrl + "?wsdl";// Connect To the web service System.IO.
                //string wsdlContents = client.DownloadString(ccc);
                string wsdlContents = client.DownloadString(ccc);
                XmlDocument wsdlDoc = new XmlDocument();
                wsdlDoc.InnerXml = wsdlContents;
                System.Web.Services.Description.ServiceDescription description = System.Web.Services.Description.ServiceDescription.Read(new XmlNodeReader(wsdlDoc));

                //Read the WSDL file describing a service.
                // System.Web.Services.Description.ServiceDescription description = System.Web.Services.Description.ServiceDescription.Read(stream);

                //Load the DOM

                //--Initialize a service description importer.
                ServiceDescriptionImporter importer = new ServiceDescriptionImporter();
                importer.ProtocolName = "Soap12"; //Use SOAP 1.2.
                importer.AddServiceDescription(description, null, null);

                //--Generate a proxy client. 

                importer.Style = ServiceDescriptionImportStyle.Client;
                //--Generate properties to represent primitive values.

                importer.CodeGenerationOptions = System.Xml.Serialization.CodeGenerationOptions.GenerateProperties;

                //Initialize a Code-DOM tree into which we will import the service.
                CodeNamespace codenamespace = new CodeNamespace();
                CodeCompileUnit codeunit = new CodeCompileUnit();
                codeunit.Namespaces.Add(codenamespace);

                //Import the service into the Code-DOM tree. 
                //This creates proxy code that uses the service.

                ServiceDescriptionImportWarnings warning = importer.Import(codenamespace, codeunit);

                if (warning == 0)
                {

                    //--Generate the proxy code
                    CodeDomProvider provider = CodeDomProvider.CreateProvider("CSharp");

                    //--Compile the assembly proxy with the 
                    //  appropriate references
                    string[] assemblyReferences = new string[]  {
                       "System.dll", 
                       "System.Web.Services.dll", 
                       "System.Web.dll", 
                       "System.Xml.dll", 
                       "System.Data.dll"};

                    //--Add parameters
                    CompilerParameters parms = new CompilerParameters(assemblyReferences);
                    parms.GenerateInMemory = true; //(Thanks for this line nikolas)
                    CompilerResults results = provider.CompileAssemblyFromDom(parms, codeunit);

                    //--Check For Errors
                    if (results.Errors.Count > 0)
                    {

                        foreach (CompilerError oops in results.Errors)
                        {
                            System.Diagnostics.Debug.WriteLine("========Compiler error============");
                            System.Diagnostics.Debug.WriteLine(oops.ErrorText);
                        }
                        throw new Exception("Compile Error Occured calling WebService.");
                    }

                    //--Finally, Invoke the web service method
                    Object wsvcClass = results.CompiledAssembly.CreateInstance(serviceName);
                    MethodInfo mi = wsvcClass.GetType().GetMethod(methodName);
                    return mi.Invoke(wsvcClass, args);
                }
                else
                {
                    return null;
                }
            }

            catch (Exception ex)
            {
                throw ex;
            }
        }

Теперь проблема возникает, когда у меня есть два разных клиентских сервера. и вызов службы с одного сервера на службу, развернутую на другом сервере. Возникают следующие два вида журнала ошибок. Не могу найти точную причину, чтобы справиться с этой проблемой.

System.Net.WebException: The request failed with HTTP status 400: Bad Request.
 at System.Web.Services.Protocols.SoapHttpClientProtocol.ReadResponse(SoapClientMessage message, WebResponse response, Stream responseStream, Boolean asyncCall)
 at System.Web.Services.Protocols.SoapHttpClientProtocol.Invoke(String methodName, Object[] parameters)
 at MarkUsageHistoryInSTJH.InsertUpdateIssueItemAditionalDetail(String csvBarcode, String csvName, String csvPMGSRN, String csvGLN, String csvMobile, String csvPhone, String csvAddressLine1, String csvAddressLine2, String csvAddressLine3, String csvIsHospital)

и

System.Net.Sockets.SocketException (0x80004005): 
A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond 172.17.13.7:80     
  at System.Net.Sockets.Socket.DoConnect(EndPoint endPointSnapshot, SocketAddress socketAddress)     

  at System.Net.ServicePoint.ConnectSocketInternal(Boolean connectFailure, Socket s4, Socket s6, Socket& socket, IPAddress& address, ConnectSocketState state, IAsyncResult asyncResult, Int32 timeout, Exception& exception)

person talalmustafa    schedule 13.12.2011    source источник
comment
У нас была аналогичная проблема, когда мы обращались к одному webservice.asmx из другого. Я могу сказать вам, что это связано с тем, что вызывающий веб-сервис должен ждать, пока другой веб-сервис отправит ответ, и это время ожидания.   -  person Dot_NET Pro    schedule 18.02.2014


Ответы (1)


Пожалуйста, выполните следующие шаги:

1) Прежде всего попробуйте получить доступ к вашему сервису, добавив ссылку на него.

Если это работает нормально, мы можем сказать, что нет проблем, связанных с доступностью и разрешением.

2) Если не работает, то проблема с подключением. --> Итак, проверьте конфигурацию вашего сервиса и попробуйте установить тайм-аут для вашего веб-сервиса. (http://social.msdn.microsoft.com/Forums/vstudio/en-US/ed89ae3c-e5f8-401b-bcc7- 333579a9f0fe/webservice-client-timeout)

3) Теперь попробуйте после установки тайм-аута. эта операция завершается успешно после вышеуказанного изменения, что означает, что теперь вы можете проверить свой метод веб-клиента (динамический вызов).

4) Если проблема не устранена, это может быть связано с задержкой в ​​сети. Проверьте задержку n/w между вашим клиентом и сервером. это поможет вам.

person Ashok Rathod    schedule 12.09.2014