2011-12-13 208 views
4

Iam動態地通過我的Web服務調用Web服務。我在我的數據庫表中存儲了serviceName,MethodToCall和參數數組,並執行這兩個方法來調用帶有.asmx擴展的動態服務url及其方法,而不在我的應用程序中添加其引用。它工作正常。System.Net.WebException:請求失敗,HTTP狀態400:錯誤請求。動態調用Web服務

以下代碼在這裏。

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; 
      } 
     } 

現在的問題排列時,我有兩個不同的客戶端服務器。並將服務從一臺服務器調用到部署在其他服務器上的服務。 Follwing發生兩種錯誤日誌。無法找到確切的共振來解決這個問題。

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) 
+0

當我們從另一個webservice.asmx訪問時,我們遇到了類似的問題。 我可以告訴你,這是因爲調用webservice必須等待其他websrvice發送響應和超時。 –

回答

0

請貫徹以下步驟:

1)首先嚐試通過增加它的引用來訪問你的服務。

它工作正常,那麼我們可以說沒有關於可訪問性和權限的問題。

2)如果它不工作,則存在連接問題。 - >因此請在您的服務中檢查配置並嘗試爲您的Web服務設置超時。 (http://social.msdn.microsoft.com/Forums/vstudio/en-US/ed89ae3c-e5f8-401b-bcc7- 333579a9f0fe/webservice-client-timeout)

3)現在嘗試設置超時後。 上述更改後,操作成功完成,即現在您可以使用Web客戶端方法(動態調用)進行檢查。

4)如果問題仍然存在,那麼這可能是網絡延遲問題。檢查客戶端和服務器之間的n/w延遲。 它會幫助你。

相關問題