【问题标题】:System.Net.WebException: The request failed with HTTP status 400: Bad Request. calling a webservice dynamicallySystem.Net.WebException:请求失败,HTTP 状态 400:错误请求。动态调用网络服务
【发布时间】:2012-01-19 05:30:20
【问题描述】:

我正在通过我的网络服务动态调用网络服务。我将 serviceName、MethodToCall 和参数数组存储在我的数据库表中,并执行这两个方法来调用具有 .asmx 扩​​展名的动态服务 url 及其方法,而无需在我的应用程序中添加其引用。它工作正常。

下面的代码在这里。

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)

【问题讨论】:

  • 当我们从另一个访问一个 webservice.asmx 时,我们遇到了类似的问题。我可以告诉你,这是因为调用 webservice 必须等待其他 websrvice 发送响应并且它超时。

标签: sql-server-2008 c#-4.0 webservice-client


【解决方案1】:

请执行以下步骤:

1) 首先尝试通过添加引用来访问您的服务。

它工作正常,那么我们可以说没有与可访问性和权限相关的问题。

2) 如果它不起作用,则说明连接有问题。 -->所以检查您的服务中的配置并尝试为您的网络服务设置超时。 (http://social.msdn.microsoft.com/Forums/vstudio/en-US/ed89ae3c-e5f8-401b-bcc7- 333579a9f0fe/webservice-client-timeout)

3)现在设置超时后尝试。 完成上述更改后,it 操作成功完成,这意味着您现在可以检查您的 Web 客户端方法(动态调用)。

4) 如果问题仍然存在,则可能是网络延迟问题。检查客户端和服务器之间的 n/w 延迟。 它会帮助你。

【讨论】:

    猜你喜欢
    • 2011-03-26
    • 2013-07-21
    • 2019-09-13
    • 2017-09-07
    • 2020-10-21
    • 2013-01-01
    • 2018-08-09
    • 2015-04-10
    • 2017-06-02
    相关资源
    最近更新 更多