如何:导入自定义 WSDL
本主题描述如何导入自定义 WSDL。若要处理自定义 WSDL,必须实现 IWsdlImportExtension 接口。
导入自定义 WSDL
实现 IWsdlImportExtension。实现 BeforeImport 方法,以便在导入元数据之前对其进行修改。实现 ImportEndpoint 和 ImportContract 方法,以便修改从元数据导入的协定和终结点。若要访问所导入的协定或终结点,请使用相应的上下文对象(WsdlContractConversionContext 或 WsdlEndpointConversionContext):
public class WsdlDocumentationImporter : IWsdlImportExtension { public void ImportContract(WsdlImporter importer, WsdlContractConversionContext context) { // Contract documentation if (context.WsdlPortType.Documentation != null) { context.Contract.Behaviors.Add(new WsdlDocumentationImporter(context.WsdlPortType.Documentation)); } // Operation documentation foreach (Operation operation in context.WsdlPortType.Operations) { if (operation.Documentation != null) { OperationDescription operationDescription = context.Contract.Operations.Find(operation.Name); if (operationDescription != null) { operationDescription.Behaviors.Add(new WsdlDocumentationImporter(operation.Documentation)); } } } } public void BeforeImport(ServiceDescriptionCollection wsdlDocuments, XmlSchemaSet xmlSchemas, ICollection<XmlElement> policy) { Console.WriteLine("BeforeImport called."); } public void ImportEndpoint(WsdlImporter importer, WsdlEndpointConversionContext context) { Console.WriteLine("ImportEndpoint called."); } }
将客户端应用程序配置为使用自定义 WSDL 导入程序。请注意,如果使用的是 Svcutil.exe,则应将此配置添加到 Svcutil.exe (Svcutil.exe.config) 的配置文件中:
<system.serviceModel> <client> <endpoint address="https://localhost:8000/Fibonacci" binding="wsHttpBinding" contract="IFibonacci" /> <metadata> <wsdlImporters> <extension type="Microsoft.WCF.Documentation.WsdlDocumentationImporter, WsdlDocumentation" /> </wsdlImporters> </metadata> </client> </system.serviceModel>
创建一个新的 WsdlImporter 实例(并将其传入包含要导入的 WSDL 文档的 MetadataSet 实例),然后调用 ImportAllContracts:
WsdlImporter importer = new WsdlImporter(metaDocs); System.Collections.ObjectModel.Collection<ContractDescription> contracts = importer.ImportAllContracts();