【问题标题】:C# .NET web service and returning list of objects that have children with a list of child objectsC# .NET Web 服务并返回具有子对象列表的对象列表和子对象列表
【发布时间】:2010-07-01 04:47:27
【问题描述】:

我正在构建一个 Web 服务来传回(艺术家)对象的列表。在艺术家对象内部有一个(专辑)对象列表。在 Album 对象内有一个歌曲列表。

所以基本上我正在构建一个大的音乐父子树。

我的问题是,如何使用 SOAP 传递它?

什么是最好的使用方法。

现在我得到的只是

<Artist>
    <Name>string</Name>
    <Albums>
        <AlbumName>string</AlbumName>
        <Album xsi:nil="true" />
    <Album xsi:nil="true" />
    </Albums>
    <Albums>
        <AlbumName>string</AlbumName>
        <Album xsi:nil="true" />
        <Album xsi:nil="true" />
    </Albums>
</Artist>

它在专辑中出现故障,但它显示了我存储的两张专辑。

任何建议将不胜感激!

【问题讨论】:

  • 您使用的是哪种列表?艺术家、专辑和歌曲是否一样
  • 我最终会从 Web 服务调用返回 List。艺术家包含列表,专辑包含列表。我试图做泛型 List 但没有奏效。

标签: c# soap service object


【解决方案1】:

好消息是 .NET Web 服务将为您处理 XML。您所要做的就是将返回类型声明为List&lt;Artist&gt; 或类似的。 Web 服务将负责将您的对象序列化为 XML。不清楚您是否正在滚动自己的 XML。

您粘贴的 XML 看起来像是来自 WSDL。

在 Visual Studio 中运行您的项目,然后浏览到 Web 服务 .asmx 页面。你会找到类似的东西。

要使用 HTTP POST 协议测试操作,请单击“调用”按钮。

单击该按钮以运行您的方法。

如果您自己的 WebMethod 没有按预期工作,不妨试试这个简单的测试 WebMethod: The result will be this XML doc.

  [WebMethod]
  public List<Artist> ListAllArtists()
  {
      List<Artist> all = new List<Artist>();
      Album one = new Album { Name = "hi", SongNames = new List<string> { "foo", "bar", "baz" } };
      Album two = new Album { Name = "salut", SongNames = new List<string> { "green", "orange", "red" } };
      Album three = new Album { Name = "hey", SongNames = new List<string> { "brown", "pink", "blue" } };
      Album four = new Album { Name = "hello", SongNames = new List<string> { "apple", "orange", "pear" } };

      all.Add(new Artist { Albums = new List<Album> { one }, Name = "Mr Guy" });
      all.Add(new Artist { Albums = new List<Album> { two }, Name = "Mr Buddy" });
      all.Add(new Artist { Albums = new List<Album> { three, four }, Name = "Mr Friend" });

      return all;        
  }

public class Artist
{
    public List<Album> Albums;
    public string Name;
}

public class Album
{
    public string Name;
    public List<string> SongNames;
}

【讨论】:

  • 我明确地不想扮演我自己的 XML 角色。我从 .asmx 页面复制了该代码
  • 谢谢...其实我已经很接近了!
  • 即使我有类似的 Web 服务,我也想知道如何在 Windows 窗体应用程序中使用它。我该怎么做?
【解决方案2】:

类似这样的:

[DataContract]
class Artist
{
   .....
   [DataMember]
   public List<Album> Albums;
   .....
}

[DataContract]
class Album
{
   .....
   int ID;
   .....
   [DataMember]
   public List<Song> Songs;
   .....
}

[DataContract]
class Song
{
   .....
   int ID;
   .....
   [DataMember]
   public string Title;
   .....
}

注意:这只是为了展示如何让你的对象序列化。修改它以使用属性而不是公共字段等...

您只需要实现 WCF 服务并使用List&lt;Artist&gt;

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-09-24
    • 1970-01-01
    • 2011-09-07
    • 1970-01-01
    • 2017-03-06
    • 1970-01-01
    • 2018-12-02
    相关资源
    最近更新 更多