从多个Web引用共享数据类型

假设供应商提供了两个单独的Web服务,它们共享相同的数据类型和相同的命名空间。

例如,以下Web服务都包含类似的对象,例如TestCredentials对象:

  • TestWebservice / Testwebservice1.asmx
  • TestWebservice / Testwebservice2.asmx

使用Web引用将这些包含到Visual Studio中我最终得到:

  • Testwebservice1.TestCredentials
  • Testwebservice2.TestCredentials

当我真正想要的是:

  • Testwebservice.TestCredentials

在处理Web引用时,Visual Studio中是否有任何方法将这两个Web服务链接在一起,以便生成的代理类相同(并在同一名称空间中)?

另一个可能的选项(以及wsdl.exe / sharetypes)是使用Visual Studio 2008并使用“添加服务引用”。 “添加服务引用”对话框提供了重用类型的选项。

您必须使用带有/ sharetypes开关的wsdl.exe程序手动生成代理类。

你应该做什么而不是在visual studio中添加web引用是使用wsdl.exe命令行工具生成一个代理类,然后你可以编辑该代理类来接受一个URL,而不是在不同的命名空间中有两个带有硬编码的url。

是的,你可以这样做。 我们称之为数据编组,但在本例中我将其称为合并者。

您会注意到WSDL生成的类是部分的,我们创建一个(Web引用名称).cs文件,并具有以下内容:

下面是您创建的文件,而不是WSDL生成的文件

WebReference1.cs

public partial class WebReferenceName1 : System.Web.Services.Protocols.SoapHttpClientProtocol { // take the methodname and append Local to the end public Consolidated.ReturnType MethodName1Local(params) { // redirect the return value of the call to the consolidation method and return the new value return Consolidation.Convert(this.MethodName1(params); } } 

然后第二个Web服务

WebReference2.cs

 public partial class WebReferenceName2 : System.Web.Services.Protocols.SoapHttpClientProtocol { // take the methodname and append Local to the end public Consolidated.ReturnType MethodName2Local(params) { // redirect the return value of the call to the consolidation method and return the new value return Consolidation.Convert(this.MethodName2(params); } } 

现在是从两种类型转换而来的类

Consolidator.cs

 public class Consolidation { // Input from Web Reference #1 public static Consolidated.ReturnType Convert(WebReferenceName1.ReturnType valuetoConvert) { // Convert from valuetoConvert to Consolidated.ReturnType convertedValue = (conversion of valuetoConvert to Consolidated.ReturnType); return convertedValue; } // Input from Web Reference #2 public static Consolidated.ReturnType Convert(WebReferenceName2.ReturnType valuetoConvert) { // Convert from valuetoConvert to Consolidated.ReturnType convertedValue = (conversion of valuetoConvert to Consolidated.ReturnType); return convertedValue; } } 

基本上,您将方法添加到Web引用,调用{WebMethod} Local()方法,并通过Consolidator进行路由,并将简单的WSDL生成的类转换为您可以实际使用的类。

Consolidated.ReturnType是您在本地项目中定义的,它是WSDL在Web引用下生成的数据类型的本地版本。 通常,“转换”只是属性从一种类型复制到另一种类型的克隆/属性。

您可以创建一个引用所有Web服务的简单.disco文件。 它只是每个Web服务的简单contractRef。

Visual Studio将共享类型,只要它们使用相同的xml命名空间即可。

我不相信,至少不是没有修改自动生成的reference.cs代码。

我想到的是一些解决方法:1)创建一个基于reflection的复制方法,根据属性名称复制值,或者2)如果您使用的是.NET 3.5,请编写一个扩展方法来复制这两种类型。