C# wsdl接口调用事例
时间: 2024-02-05 18:09:03 浏览: 185
以下是C#调用wsdl接口的三种方法示例:
1. 使用Visual Studio自动生成代理类:
```csharp
// 引用WebService接口
using WebServiceNamespace;
// 创建代理类实例
WebServiceClient client = new WebServiceClient();
// 调用接口方法
string result = client.MethodName(parameter);
```
2. 使用命令行工具wsdl.exe生成代理类:
```shell
// 打开命令提示符
// 进入wsdl.exe所在目录
// 执行以下命令生成代理类
wsdl /language:c# /out:生成类的物理路径 /url:WebService接口URL或wsdl文件路径
// 在代码中引用生成的代理类
using WebServiceNamespace;
// 创建代理类实例
WebServiceClient client = new WebServiceClient();
// 调用接口方法
string result = client.MethodName(parameter);
```
3. 手动解析wsdl文件:
```csharp
// 引用System.Web.Services和System.Web.Services.Description命名空间
using System.Web.Services;
using System.Web.Services.Description;
using System.Xml;
// 创建WebService描述文件的URL
string wsdlUrl = "WebService接口URL或wsdl文件路径";
// 创建ServiceDescription对象
ServiceDescription serviceDescription = ServiceDescription.Read(wsdlUrl);
// 创建ServiceDescriptionImporter对象
ServiceDescriptionImporter importer = new ServiceDescriptionImporter();
importer.ProtocolName = "Soap"; // 指定协议为Soap
// 添加ServiceDescription对象
importer.AddServiceDescription(serviceDescription, null, null);
// 创建CodeNamespace对象
CodeNamespace codeNamespace = new CodeNamespace("WebServiceNamespace");
// 创建CodeCompileUnit对象
CodeCompileUnit codeCompileUnit = new CodeCompileUnit();
codeCompileUnit.Namespaces.Add(codeNamespace);
// 生成代理类代码
ServiceDescriptionImportWarnings warnings = importer.Import(codeNamespace, codeCompileUnit);
// 使用CodeDomProvider编译代理类
CodeDomProvider codeDomProvider = CodeDomProvider.CreateProvider("CSharp");
CompilerParameters compilerParameters = new CompilerParameters();
compilerParameters.GenerateExecutable = false;
compilerParameters.GenerateInMemory = true;
CompilerResults compilerResults = codeDomProvider.CompileAssemblyFromDom(compilerParameters, codeCompileUnit);
// 获取生成的代理类类型
Type proxyType = compilerResults.CompiledAssembly.GetTypes().FirstOrDefault(t => t.Name == "WebServiceClient");
// 创建代理类实例
object proxyInstance = Activator.CreateInstance(proxyType);
// 调用接口方法
MethodInfo method = proxyType.GetMethod("MethodName");
string result = (string)method.Invoke(proxyInstance, new object[] { parameter });
```
阅读全文
相关推荐
















