使用C#动态调用SOAP

时间:2016-01-01 18:06:16

标签: c# asp.net web-services soap dynamically-generated

我使用以下代码动态调用SOAP方法。它在服务输入为ONE(1)时有效。当我将输入增加到2时,它返回错误。

不知道为什么会这样。

我提到这个链接来构建这个.. http://www.codeproject.com/Articles/18950/Dynamic-Discovery-and-Invocation-of-Web-Services

我的SOAP服务:

[WebMethod]
    public string UpdateMapString(string status, string astationid)
    {
     return string.Format("Update Completed");
    }

这是我的C#代码调用SOAP服务。

主要功能:

  private MethodInfo[] methodInfo;
        private ParameterInfo[] param;
        private Type service;
        private Type[] paramTypes;
        public List<Type> myproperty = new List<Type>();
        private string MethodName = "";
        public List<string> treews = new List<string>();
        public List<string> treeParameters = new List<string>();

        public static void Main(string[] args)
        {
            Program a = new Program();
            a.DynamicInvocation();
            a.selectMethod();
            a.invoke();

            Console.ReadLine();

        }

致电服务:

  public  void DynamicInvocation()
    {
        try
        {

            Uri uri = new Uri("http://localhost:50167/Service.asmx?WSDL");

            WebRequest webRequest = WebRequest.Create(uri);
            System.IO.Stream requestStream = webRequest.GetResponse().GetResponseStream();
            // Get a WSDL file describing a service
            ServiceDescription sd = ServiceDescription.Read(requestStream);
            string sdName = sd.Services[0].Name;
            // Add in tree view
            // treeWsdl.Nodes.Add(sdName);
            treews.Add(sdName);
            Console.WriteLine("Service Name: " + sdName);

           // messageTextBox.Text += "Generating Proxy \r\n";
           // progressBar1.PerformStep();

            // Initialize a service description servImport
            ServiceDescriptionImporter servImport = new ServiceDescriptionImporter();
            servImport.AddServiceDescription(sd, String.Empty, String.Empty);
            servImport.ProtocolName = "Soap";
            servImport.CodeGenerationOptions = CodeGenerationOptions.GenerateProperties;

          //  messageTextBox.Text += "Generating assembly  \r\n";
          //  progressBar1.PerformStep();

            CodeNamespace nameSpace = new CodeNamespace();
            CodeCompileUnit codeCompileUnit = new CodeCompileUnit();
            codeCompileUnit.Namespaces.Add(nameSpace);
            // Set Warnings
            ServiceDescriptionImportWarnings warnings = servImport.Import(nameSpace, codeCompileUnit);

            if (warnings == 0)
            {
                StringWriter stringWriter = new StringWriter(System.Globalization.CultureInfo.CurrentCulture);
                Microsoft.CSharp.CSharpCodeProvider prov = new Microsoft.CSharp.CSharpCodeProvider();
                prov.GenerateCodeFromNamespace(nameSpace, stringWriter, new CodeGeneratorOptions());

           //     messageTextBox.Text += "Compiling assembly \r\n";
           //     progressBar1.PerformStep();

                // Compile the assembly with the appropriate references
                string[] assemblyReferences = new string[2] { "System.Web.Services.dll", "System.Xml.dll" };
                CompilerParameters param = new CompilerParameters(assemblyReferences);
                param.GenerateExecutable = false;
                param.GenerateInMemory = true;
                param.TreatWarningsAsErrors = false;
                param.WarningLevel = 4;

                CompilerResults results = new CompilerResults(new TempFileCollection());
                results = prov.CompileAssemblyFromDom(param, codeCompileUnit);
                Assembly assembly = results.CompiledAssembly;
                service = assembly.GetType(sdName);


                methodInfo = service.GetMethods();


                foreach (MethodInfo t in methodInfo)
                {
                    if (t.Name == "Discover")
                        break;
                    Console.WriteLine(t.Name);

                }
            }


            //    messageTextBox.Text += warnings;
        }
        catch (Exception ex)
        {
            Console.WriteLine(ex.ToString());
          //  messageTextBox.Text += "\r\n" + ex.Message + "\r\n\r\n" + ex.ToString(); ;
          //  progressBar1.Value = 70;
        }
    }

获取方法:

 public void selectMethod()
        {

                treeParameters.Add(treews[0]);
                 MethodName = methodInfo[0].Name;
                param = methodInfo[0].GetParameters();
            /// myProperty.add = param[e.Node.Index].ParameterType;
            myproperty.Add(param[0].ParameterType);
            // Console.WriteLine("This is param: " + param[0].ToString());
            //      myProperty = new properties(param.Length);

            // Get the Parameters Type
            paramTypes = new Type[param.Length];
                for (int i = 0; i < paramTypes.Length; i++)
                {
                    paramTypes[i] = param[i].ParameterType;
                }

                foreach (ParameterInfo temp in param)
                {
                treeParameters.Add(temp.ParameterType.Name + "  " + temp.Name);

                }

        }

调用服务(此功能中的错误)

  public void invoke()
        {
            Console.WriteLine("Invoke:");

            object[] param1 = new object[param.Length];

            try
            {

                for (int i = 0; i < param.Length; i++)
                {
                    //param1[i] = Convert.ChangeType(myProperty.MyValue[i], myProperty.TypeParameter[i]);
                 //   Console.WriteLine(myproperty[i].ToString());
                    param1[i] = Convert.ChangeType("10", typeof(string));
                }

                foreach (MethodInfo t in methodInfo)
                {
                    //Console.WriteLine("Tname: " + t.Name.ToString());


                    if (t.Name == MethodName)
                    {
                        //Invoke Method
                        Object obj = Activator.CreateInstance(service);

                        //*****************error at this line
                        Object response = t.Invoke(obj, param1);
                        //*****************error at this line

                        //   Console.WriteLine(t.Name);
                        Console.WriteLine(response.ToString());
                        break;
                    }
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message.ToString());
                //MessageBox.Show(ex.Message, "Warning", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

0 个答案:

没有答案