当前位置:网站首页>Simulate soapUI and obtain the service class and method of WebService interface

Simulate soapUI and obtain the service class and method of WebService interface

2022-06-21 04:40:00 Sri Lanka internal medicine

Last one C# obtain WebService Interface [WebMethod]

C# obtain WebService Interface [WebMethod]_ S internal medicine blog -CSDN Blog _c# webservice Interface call

This time WebService The properties of related classes and methods are shown .

New form application DetailWebServiceDemo, Default Form1 Rename it to FormDetailWebService.

Add pair System.Web.Services Reference to class library

forms FormDetailWebService The design is shown in the picture :

  newly build Soap Automatically generated and reflected key class files SoapUtil.cs

SoapUtil The class source program is as follows :

using System;
using System.Collections.Generic;
using System.CodeDom;
using System.CodeDom.Compiler;
using System.IO;
using System.Net;
using System.Reflection;
using System.Web.Services.Description;
using System.Xml.Serialization;
using System.Text;
using System.Xml;

namespace DetailWebServiceDemo
{
    /// <summary>
    ///  Get dynamic WebService All the ways 
    ///  Sri Lanka internal medicine  2022-06-08
    /// </summary>
    public class SoapUtil
    {
        /// <summary>
        ///  obtain WebService All of the interfaces WebMethod Method 
        ///  adopt WebService The properties of the method are 【System.Web.Services.Protocols.SoapDocumentMethodAttribute】
        ///  According to the characteristics SoapDocumentMethodAttribute To filter out all WebMethod Method 
        /// </summary>
        /// <param name="url"></param>
        public static List<MethodInfo> GetAllWebMethodsFromService(string url, out string className, out Type type)
        {
            className = "SoapWebService";
            if (!url.EndsWith("?wsdl", StringComparison.CurrentCultureIgnoreCase))
            {
                url = url + "?wsdl";
            }
            string tempUrl = url;
            if (url.EndsWith("?wsdl", StringComparison.CurrentCultureIgnoreCase))
            {
                tempUrl = url.Substring(0, url.Length - 5);
            }
            className = Path.GetFileNameWithoutExtension(tempUrl);
            
            // 1.  Use  WebClient  download  WSDL  Information .
            WebClient web = new WebClient();
            Stream stream = web.OpenRead(url);
            // 2.  Create and format  WSDL  file .
            ServiceDescription description = ServiceDescription.Read(stream);
            // 3.  Create a client proxy class .
            ServiceDescriptionImporter importer = new ServiceDescriptionImporter();
            //  Specified access protocol .
            importer.ProtocolName = "Soap";
            //  Generate client agent .
            importer.Style = ServiceDescriptionImportStyle.Client;
            importer.CodeGenerationOptions = CodeGenerationOptions.GenerateProperties | CodeGenerationOptions.GenerateNewAsync;
            //  add to  WSDL  file .
            importer.AddServiceDescription(description, null, null);
            // 4.  Use  CodeDom  Compile the client proxy class .
            //  Add a namespace to the proxy class , The default is global space .
            CodeNamespace nmspace = new CodeNamespace();
            CodeCompileUnit unit = new CodeCompileUnit();
            unit.Namespaces.Add(nmspace);
            ServiceDescriptionImportWarnings warning = importer.Import(nmspace, unit);
            CodeDomProvider provider = CodeDomProvider.CreateProvider("CSharp");

            Microsoft.CSharp.CSharpCodeProvider
            //CodeTypeDeclaration codeTypeDeclaration = new CodeTypeDeclaration(className);
             Declare a new generated code attribute
            //GeneratedCodeAttribute generatedCodeAttribute = new GeneratedCodeAttribute("System.Web.Services", "4.8.3761.0");
             Use the generated code attribute members in the attribute declaration
            //CodeAttributeDeclaration codeAttrDecl = new CodeAttributeDeclaration(generatedCodeAttribute.GetType().Name,
            //        new CodeAttributeArgument(new CodePrimitiveExpression(generatedCodeAttribute.Tool)),
            //        new CodeAttributeArgument(new CodePrimitiveExpression(generatedCodeAttribute.Version)));
            //codeTypeDeclaration.CustomAttributes.Add(codeAttrDecl);
            //provider.GenerateCodeFromType(codeTypeDeclaration, Console.Out, new CodeGeneratorOptions());

            CompilerParameters parameter = new CompilerParameters();
            parameter.GenerateExecutable = false;
            parameter.GenerateInMemory = true;// Generate output in memory 
            //  You can specify any file name you want .
            parameter.OutputAssembly = AppDomain.CurrentDomain.BaseDirectory + className + ".dll";
            parameter.ReferencedAssemblies.Add("System.dll");
            parameter.ReferencedAssemblies.Add("System.XML.dll");
            parameter.ReferencedAssemblies.Add("System.Web.Services.dll");
            parameter.ReferencedAssemblies.Add("System.Data.dll");
            //  Generate dll file , And will WebService Information written to dll Inside 
            CompilerResults result = provider.CompileAssemblyFromDom(parameter, unit);

            Assembly assembly = result.CompiledAssembly;
            type = assembly.GetType(className);
            List<MethodInfo> methodInfoList = new List<MethodInfo>();
            MethodInfo[] methodInfos = type.GetMethods();
            for (int i = 0; i < methodInfos.Length; i++)
            {
                MethodInfo methodInfo = methodInfos[i];
                //WebMethod The properties of the method are :System.Web.Services.Protocols.SoapDocumentMethodAttribute 
                Attribute attribute = methodInfo.GetCustomAttribute(typeof(System.Web.Services.Protocols.SoapDocumentMethodAttribute));
                if (methodInfo.MemberType == MemberTypes.Method && attribute != null)
                {
                    methodInfoList.Add(methodInfo);
                }
            }
            return methodInfoList;
        }
    }
}

forms FormDetailWebService The main procedures are as follows :

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace DetailWebServiceDemo
{
    public partial class FormDetailWebService : Form
    {
        public FormDetailWebService()
        {
            InitializeComponent();
            // Usable WebService Interface list  https://blog.csdn.net/u012408847/article/details/83027861
        }

        private void btnGetWebMethod_Click(object sender, EventArgs e)
        {
            tvAllMethods.Nodes.Clear();
            string url = txtUrl.Text.Trim();
            string className;
            try
            {
                Type typeService;
                List<MethodInfo> methodInfos = SoapUtil.GetAllWebMethodsFromService(url, out className, out typeService);
                TreeNode rootNode = new TreeNode(" service name :" + className);// Take the class name as the root node 
                rootNode.Tag = typeService;
                tvAllMethods.Nodes.Add(rootNode);
                for (int i = 0; i < methodInfos.Count; i++)
                {
                    MethodInfo methodInfo = methodInfos[i];
                    TreeNode treeNode = new TreeNode($"{methodInfo.Name}");
                    // Set up Tag The tag is method information 
                    treeNode.Tag = methodInfo;
                    rootNode.Nodes.Add(treeNode);
                }
                tvAllMethods.ExpandAll();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, " error ");
            }
        }

        private void tvAllMethods_AfterSelect(object sender, TreeViewEventArgs e)
        {
            rtxtMethodInfo.Clear();
            if (e.Node.Level == 0)
            {
                // Processing the root node : Service class name 
                Type typeService = e.Node.Tag as Type;
                if (typeService != null)
                {
                    System.CodeDom.Compiler.GeneratedCodeAttribute generatedCodeAttribute = typeService.GetCustomAttribute<System.CodeDom.Compiler.GeneratedCodeAttribute>();
                    //MessageBox.Show($"Tool:【{generatedCodeAttribute.Tool}】, Version:【{generatedCodeAttribute.Version}】");
                    System.Web.Services.WebServiceBindingAttribute webServiceBindingAttribute = typeService.GetCustomAttribute<System.Web.Services.WebServiceBindingAttribute>();
                    //MessageBox.Show($"Name:【{webServiceBindingAttribute.Name}】\nNamespace:【{webServiceBindingAttribute.Namespace}】\nLocation:【{webServiceBindingAttribute.Location}】");
                    rtxtMethodInfo.AppendText($"{e.Node.Text}\n");
                    rtxtMethodInfo.AppendText($" Generating code features :Tool:【{generatedCodeAttribute.Tool}】, Version:【{generatedCodeAttribute.Version}】\n");
                    rtxtMethodInfo.AppendText($" Service binding features : Binding name :【{webServiceBindingAttribute.Name}】\n Namespace :【{webServiceBindingAttribute.Namespace}】\n Binding location :【{webServiceBindingAttribute.Location}】\n");
                }
                return;
            }
            MethodInfo methodInfo = e.Node.Tag as MethodInfo;
            if (methodInfo == null)
            {
                return;
            }
            System.Web.Services.Protocols.SoapDocumentMethodAttribute attribute = methodInfo.GetCustomAttribute(typeof(System.Web.Services.Protocols.SoapDocumentMethodAttribute)) as System.Web.Services.Protocols.SoapDocumentMethodAttribute;
            ParameterInfo[] parameterInfos = methodInfo.GetParameters();
            rtxtMethodInfo.AppendText($"{methodInfo.ToString()}\n");
            rtxtMethodInfo.AppendText($" Interface method name :【{methodInfo.Name}】\n");
            rtxtMethodInfo.AppendText($" Interface return type :【{methodInfo.ReturnType}】\n");
            rtxtMethodInfo.AppendText($" Number of interface parameters :【{parameterInfos.Length}】\n");
            for (int i = 0; i < parameterInfos.Length; i++)
            {
                rtxtMethodInfo.AppendText($"  ---> Parameters 【{i + 1}】:【{parameterInfos[i].ToString()}】\n");
            }
            if (attribute != null)
            {
                rtxtMethodInfo.AppendText($"SoapDocumentMethodAttribute characteristic :\n");
                rtxtMethodInfo.AppendText($"  --->HTTP Header action :【{attribute.Action}】\n");
                rtxtMethodInfo.AppendText($"  ---> Operation binding :【{attribute.Binding}】\n");
                rtxtMethodInfo.AppendText($"  ---> Request element name :【{attribute.RequestElementName}】\n");
                rtxtMethodInfo.AppendText($"  ---> Request namespace :【{attribute.RequestNamespace}】\n");
                rtxtMethodInfo.AppendText($"  ---> Response element name :【{attribute.ResponseElementName}】\n");
                rtxtMethodInfo.AppendText($"  ---> Response namespace :【{attribute.ResponseNamespace}】\n");
                rtxtMethodInfo.AppendText($"  ---> Encapsulate parameter styles :【{attribute.ParameterStyle}】\n");
                rtxtMethodInfo.AppendText($"  ---> Binding schema styles :【{attribute.Use}】\n");
            }
            rtxtMethodInfo.AppendText($" Overall interface description :\n{methodInfo.ReturnType} {methodInfo.Name}({string.Join(",", parameterInfos.Select(p => p.ToString()))})");
        }
    }
}

The program runs as shown in the figure

原网站

版权声明
本文为[Sri Lanka internal medicine]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/172/202206210435231787.html