当前位置:网站首页>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 :


边栏推荐
- Get verification code
- Ctfshow SQL injection (231-253)
- Recommended temporary online image compression tool
- Colab使用教程(超级详细版)及Colab Pro/Pro+评测
- Tita: Xinrui group uses one-to-one talk to promote the success of performance change
- 是“凯撒密码”呀。(*‘▽‘*)*
- A simple understanding of consistent hash
- Cesium:CesiumLab制作影像切片与切片加载
- How to implement a custom jdbc driver in only four steps?
- XOR prefix and +map maintenance
猜你喜欢

Ctfshow SQL injection (211-230)

Tree array explanation

C盘无损移动文件

SQL notes

Small program input element moving up

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

PowerShell:因为在此系统上禁止运行脚本,解决方法

2022 ICLR | CONTRASTIVE LEARNING OF IMAGE- AND STRUCTURE BASED REPRESENTATIONS IN DRUG DISCOVERY

PowerShell plus domain add computer module

Powershell 加域 Add-Computer模块
随机推荐
Crawler scrapy framework learning 2
Cesium:CesiumLab制作影像切片与切片加载
Implementation of article list function on PHP 18 home page
Collection of wrong questions in soft test -- morning questions in the first half of 2010
力扣刷题647.回文子串
[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
SEO specification
Sword finger offer 56 - I. number of occurrences in the array
Powershell 加域 Add-Computer模块
【Try to Hack】upload-labs通关(暂时写到12关)
promise处理js多线程全部获得结果后同一处理结果
Conception d'un système basé sur MVC avec javaswing JDBC
How to implement a custom jdbc driver in only four steps?
Serial communication learning
小C的记事本
Common terms of electromagnetic compatibility
[sword finger offer] interview question 25 Merge two ordered linked lists
How to use redis
Get verification code
PHP development 16 exit module