System.Net.WebException: Request failed with HTTP status 400: Invalid request. web service call dynamically

Iam dynamically calls a web service through my web service. I saved the serviceName, MethodToCall, and an array of parameters in my database table and performed these two methods to call the dynamic service url with the .asmx extension and its method without adding a link to my application. It works great.

The following code is here.

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

Now the problem is resolved when I have two different client servers. and calling the service from one server to a service deployed on another server. The Follwing error log appears. I can not find the exact reason to cope with this problem.

 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) 

and

 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) 
+4
source share
1 answer

Follow these steps:

1) First of all, try contacting your service by adding a link to it.

This works well, then we can say that there is no problem with accessibility and resolution.

2) If it does not work, there is a connection problem. -> So check the configuration in your service and try setting a timeout for your web service. ( http://social.msdn.microsoft.com/Forums/vstudio/en-US/ed89ae3c-e5f8-401b-bcc7- 333579a9f0fe / web service-client-timeout)

3) Now try setting a timeout. this operation succeeds after the above change, which means that now you can test your web client method (dynamic call).

4) If the problem still persists, it may be a network latency problem. Check the n / w delay between your client and server. it will help you.

0
source

Source: https://habr.com/ru/post/1386074/


All Articles