.NET SOAP常见类型
时间:2020-03-06 14:39:52 来源:igfitidea点击:
创建Web服务时,有没有一种方法可以指定要使用的类型?具体来说,我希望能够在客户端和服务器上使用相同的类型,以减少代码重复。
在简化的示例中:
public class Name { public string FirstName {get; set;} public string Surname { get; set; } public override string ToString() { return string.Concat(FirstName, " ", Surname); } }
我不想在课堂上重新编码功能。另一件事是,存在的用于操作此类的代码将无法在客户端运行,因为生成的客户端类将是另一种类型。
解决方案
如果要在Web服务和客户端之间共享类型或者结构,请向Web服务项目中添加一个公共结构,如下所示:
public struct Whatever { public string A; public int B; }
然后向Web服务添加一个以该结构作为返回类型的方法:
[WebMethod] public Whatever GiveMeWhatever() { Whatever what = new Whatever(); what.A = "A"; what.B = 42; return what; }
更新客户端的网络参考之后,我们将可以在客户端应用程序中创建类型为Whatever的结构,如下所示:
Webreference.Whatever what = new Webreference.Whatever(); what.A = "that works?"; what.B = -1; // FILENOTFOUND
这种技术使我们可以维护需要在一个地方(Web服务项目)来回传递的任何结构的定义。
好的,我知道这是SOAP的明确设计决定,因此我们实际上并不需要这样做。我发现以下页面解释了原因:
Services share schema and contract, not class. Services interact solely on their expression of structures through schemas and behaviors through contracts. The service's contract describes the structure of messages and ordering constraints over messages. The formality of the expression allows machine verification of incoming messages. Machine verification of incoming messages allows you to protect the service's integrity. Contracts and schemas must remain stable over time, so building them flexibly is important.
话虽如此,还有另外两种可能性:
- 在Visual Studio中或者使用wsdl.exe生成Web引用。然后进入生成的Reference.cs(或者.vb)文件,并明确删除该类型。然后重定向到另一个程序集中所需的类型。
- 我们可以通过wsdl.exe和/ sharetypes参数在客户端的Web服务之间共享类型。