【问题标题】:Service Reference is using Arrays instead of List<Type>, even when settings say to use List服务参考使用数组而不是 List<Type>,即使设置说使用 List
【发布时间】:2011-03-10 17:39:41
【问题描述】:

我正在使用 Visual Studio 2010,并且我有一个对我们创建的 Web 服务的服务引用。我们的方法返回包含通用 List 属性的对象:

public class ExampleResponse
{
  private System.Collections.Generic.List<int> intValues;

  [WCF::MessageBodyMember(Name = "IntValues")]
  public System.Collections.Generic.List<int> IntValues    
  {
    get { return intValues; }
    set { intValues= value; }
  }
}

在客户端,它使用 int[] 而不是 List 创建一个 References.cs 文件:

[System.ServiceModel.MessageBodyMemberAttribute(Namespace="SomeNamespace", Order=0)]
[System.Xml.Serialization.XmlArrayAttribute(IsNullable=true)]
[System.Xml.Serialization.XmlArrayItemAttribute(Namespace="http://schemas.microsoft.com/2003/10/Serialization/Arrays", IsNullable=false)]
public int[] IntValues;

在服务引用设置中,集合类型设置为使用列表,而不是数组。然而,它仍在这样做。

任何有关如何解决此问题的信息都会非常有帮助,但似乎没有任何意义。

【问题讨论】:

    标签: c# web-services


    【解决方案1】:

    您添加了“服务参考”还是“网络参考”?似乎代理是使用 XmlSerializer 而不是 DataContractSerializer 生成的。如果使用了 DataContractSerializer,您将拥有 System.Runtime.Serialization... 属性而不是 Xml.Serialization... 属性。您究竟是如何生成此网络参考的?更新后的 XmlSerializer 会将所有集合转换为数组,因为 Datacontract 序列化程序知道如何生成 .Net DataTypes。添加 Web 引用使用 XmlSerializer BTW。

    另外,我很好奇您对 MessageBodyMember 的使用。您为什么要尝试生成自己的 MessageContracts。使用 MessageContracts 可能非常危险,尤其是在您不知道自己在做什么的情况下。

    请尝试以下方法:

    [DataContract]
    public class ExampleResponse
    {
        private System.Collections.Generic.List<int> intValues;
    
        [DataMember]
        public System.Collections.Generic.List<int> IntValues
        {
            get { return intValues; }
            set { intValues = value; }
        }
    }
    

    看看这对您有什么作用并告诉我们。

    【讨论】:

    • 引用是通过右键单击项目并选择“添加服务引用...”来创建的。当对话框出现以查找 Web 服务时,我没有选择底部的 Web Reference 选项。我会检查您的其他建议,但这一直有效 - 它来自我们“继承”的网络服务。
    • 好的,知道了。你的评论让我走上了一条我以前没有想到的道路。我们有一个没有 DataContract 属性的枚举,所以 VS2010 在没有告诉我的情况下创建了一个 WebReference。我也理解你说的处理我们自己的消息合同,这很丑。
    • 很高兴我能帮上忙。快乐编码
    • VS2013 - 移除ServiceReference --> 添加服务参考-->Advanced-->Collection type: = System.Collections.Generic.List.
    【解决方案2】:

    在添加服务参考中,您可以选择用于集合的类型。出于某种原因,Array 是默认值。更改后,我不得不删除整个引用并重新添加它,从一开始就选择列表。事后更改它时我遇到了奇怪的问题。

    【讨论】:

    • 我已经做到了这一点,方法是在 Collection 值甚至可以创建引用之前设置它。但我仍然得到数组。
    猜你喜欢
    • 2021-02-23
    • 1970-01-01
    • 2017-01-09
    • 2012-12-31
    • 2021-11-26
    • 2015-09-29
    • 2017-03-18
    • 1970-01-01
    相关资源
    最近更新 更多