如何为Web服务声明复杂的嵌套C#类型

时间:2009-10-28 22:29:35

标签: web-services asmx

我想创建一个接受复杂嵌套类型的服务。在我创建的asmx文件示例中:

[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
// To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line. 
// [System.Web.Script.Services.ScriptService]
public class ServiceNest : System.Web.Services.WebService
{
   public class Block
   {
      [XmlElement(IsNullable = false)]
      public int number;
   }

   public class Cell
   {
      [XmlElement(IsNullable = false)]
      public Block block;
   }

   public class Head
   {
      [XmlElement(IsNullable = false)]
      public Cell cell;
   }

   public class Nest
   {
      public Head head;
   }

   [WebMethod]
   public void TakeNest(Nest nest)
   {
   }

}

当我在IE中查看asmx文件时,测试页面将示例SOAP post请求显示为:

<?xml version="1.0" encoding="utf-8"?>
<soap:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">
  <soap:Body>
    <TakeNest xmlns="http://schemas.intellicorp.com/livecompare/">
      <nest>
        <head>
          <cell>
            <block xsi:nil="true" />
          </cell>
        </head>
      </nest>
    </TakeNest>
  </soap:Body>
</soap:Envelope>

它没有扩展&lt; block&gt;进入其号码成员。

查看WSDL,所有类型都很好看。那么这只是后期演示页面创建者的限制吗?

感谢。

3 个答案:

答案 0 :(得分:1)

但那些元素 ARE 为null。你需要在它们出现之前构造它们,否则它们只是空的。

答案 1 :(得分:0)

正如Kevin所指出的,POST XML示例表明这些元素是零。我应该只是尝试使用Web服务。一旦我这样做,我可以看到导入器(.NET,Java或Ruby)正确创建了所有类型。毕竟,这里真的没有问题。

答案 2 :(得分:0)

.NET代码在一定数量的级别后没有放弃。

如果查看“添加Web引用”生成的代码,您会发现有一个bool numberSpecified字段。只有当客户端将其设置为true时,才会序列化该号码。

如果查看XML Schema,您会发现number元素可能不存在。如果它是引用类型,则可以通过null值在客户端中表示。由于它是int,因此需要此附加标志来指示是否序列化此可选值。