当前位置:网站首页>C # get all callable methods of WebService interface [webmethod]
C # get all callable methods of WebService interface [webmethod]
2022-06-13 04:40:00 【Sri Lanka internal medicine】
C# Get the specified WebService Interface , The tree graph control to which it is bound (TreeView) in , We quote the weather WebService Service as an example , Available online .
PS: The weather WeatherWebService It's a WebService, instead of WCF. If according to WCF call , The interface can never be called successfully
One 、 newly build Windows Forms application WeatherWebServiceDemo
Default Form1 Rename it to FormWeather, forms FormWeather The design is shown in the picture

Is a tree diagram control tvAllMethods The binding event AfterSelect
Two 、 Right click quote ----> Add service reference

Click on “ senior ” ----> add to Web quote , Input Url by
http://www.webxml.com.cn/WebServices/WeatherWebService.asmx?wsdl
Click to go to

Click on “ Add reference ” that will do .
3、 ... and 、 New class file SoapUtil.cs
SoapUtil The 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;
namespace WeatherWebServiceDemo
{
/// <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)
{
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");
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 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;
}
}
}
Four 、 forms FormWeather The main procedures are as follows :
( Ignore part of the class code automatically generated by the designer )
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 WeatherWebServiceDemo
{
public partial class FormWeather : Form
{
public FormWeather()
{
InitializeComponent();
}
private void btnGetWebMethod_Click(object sender, EventArgs e)
{
tvAllMethods.Nodes.Clear();
string url = txtUrl.Text.Trim();
string className;
try
{
List<MethodInfo> methodInfos = SoapUtil.GetAllWebMethodsFromService(url, out className);
TreeNode rootNode = new TreeNode(" service name :" + className);// Take the class name as the root node
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)
{
// Do not consider the root node : Service class name
return;
}
MethodInfo methodInfo = e.Node.Tag as MethodInfo;
if (methodInfo == null)
{
return;
}
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");
}
rtxtMethodInfo.AppendText($" Overall interface description :\n{methodInfo.ReturnType} {methodInfo.Name}({string.Join(",", parameterInfos.Select(p => p.ToString()))})");
}
}
}
5、 ... and 、 The program test is shown in the figure :


边栏推荐
- 约瑟夫问题
- 2022道路运输企业安全生产管理人员操作证考试题库及答案
- [flutter problem Series Chapter 67] the Solution to the problem of Routing cannot be jumped again in in dialog popup Using get plug - in in flutter
- PHP security development 15 user password modification module
- Set properties \ classes
- Redis
- 【Try to Hack】upload-labs通关(暂时写到12关)
- Recommended temporary online image compression tool
- MySQL index
- 记录一次排查问题的经过——视频通话无法接起
猜你喜欢

Powershell 加域 Add-Computer模块

EMC rectification outline

Ctfshow SQL injection (231-253)

Explanation of line segment tree

CTFSHOW SQL注入篇(211-230)

Express scaffold creation
![C#获取WebService接口的所有可调用方法[WebMethod]](/img/44/4429b78c5b8341ed9a4a08d75a683e.png)
C#获取WebService接口的所有可调用方法[WebMethod]

利用Javeswingjdbc基於mvc設計系統

Cesium:CesiumLab制作影像切片与切片加载

Introduction to applet Basics (dark horse learning notes)
随机推荐
【JS解决】leedcode 200. 岛屿数量
在线音频调节技术汇总
2022 oxidation process operation certificate examination question bank and simulation examination
2022 ICML | Pocket2Mol: Efficient Molecular Sampling Based on 3D Protein Pockets
Collection of some compatibility issues
Message scrolling JS implementation
MVP framework for personal summary
Common terms of electromagnetic compatibility
Normal distribution (Gaussian distribution)
Notes on software test for programmers -- basic knowledge of software development, operation and maintenance
Colab tutorial (super detailed version) and colab pro/pro+ evaluation
CreateAnonymousThreadX给匿名线程传递参数
D 小红的构造题
Colab使用教程(超级详细版)及Colab Pro/Pro+评测
2022 ICML | Pocket2Mol: Efficient Molecular Sampling Based on 3D Protein Pockets
Collection of wrong questions in soft test -- morning questions in the first half of 2010
Introduction to applet Basics (dark horse learning notes)
Tita performance treasure: remote one-on-one discussion
Go scheduled task cron package usage
Catalan number