【问题标题】:WCF+WebService: 2 fields are generated to represent 1 integerWCF+WebService:生成2个字段代表1个整数
【发布时间】:2011-01-10 17:52:30
【问题描述】:

在我的 WCF 服务中,我有带有“int”参数的方法:

    [OperationContract]
    PublishResult PublishEnrollmentProfile(
        string siteName, int methodId,...
        );

当我创建对此 WCF 服务的 WebService 引用时,生成了以下签名:

    [System.Web.Services.Protocols.SoapDocumentMethodAttribute("...",
        RequestNamespace="...", ResponseNamespace="...",
        Use=System.Web.Services.Description.SoapBindingUse.Literal,
        ParameterStyle=System.Web.Services.Protocols.SoapParameterStyle.Wrapped)]
    [return: System.Xml.Serialization.XmlElementAttribute(IsNullable=true)]
    public PublishResult PublishEnrollmentProfile(
        [System.Xml.Serialization.XmlElementAttribute(IsNullable=true)]
        string siteName,
        int methodId,
        [System.Xml.Serialization.XmlIgnoreAttribute()]
        bool methodIdSpecified, ...)
    {
        object[] results = this.Invoke("PublishEnrollmentProfile", new object[] {
                    siteName,
                    deployServerName,
                    methodId,
                    methodIdSpecified,
                    deviceClass,
                    deviceName,
                    registrationCode});
        return ((PublishResult)(results[0]));
    }

您可以看到,我得到了 2 个整数参数,而不是一个整数参数:整数(用于值)和布尔值(用于标记 '如果指定了值)。

这样好吗?为什么我需要第二个参数(bool)?

非常感谢!

【问题讨论】:

标签: web-services wcf wcfserviceclient


【解决方案1】:

“指定”字段仅在结构的可选参数上生成。(int、datetime、decimal 等)。所有此类变量都会生成名为 Specified 的附加变量。

由于“指定”字段仅在可选参数上生成,如果您将 PublishEnrollmentProfile 方法的参数放置在 DataContract 内并将 methodID 上的 DataMember 属性设置为 [DataMember(IsRequired=true)],则指定字段应该去离开,除非这是一个可选字段,在这种情况下您希望保持原样。

这是一个blog posting 和一些示例。

更新

所以你有你的运营合同。

[OperationContract]
PublishResult PublishEnrollmentProfile(string siteName, int methodId,...);

如果该方法的参数不是可选的,那么您应该创建一个 DataContract 并重新定义 OperationContract,如下所示:

{
   [OperationContract]
   PublishResult PublishEnrollmentProfile(PublishEnrollmentProfileRequest request);
}

然后你就有了像这样的 DataContract。

[DataContract]
public class PublishEnrollmentProfileRequest
{
    private string _siteName;
    [DataMember]
    public string siteName
    {
       get;
       set;
    }


    private int _methodId;
    [DataMember(IsRequired=True)]
    public int methodId
    {
       get;
       set;
    }

    .
    .
    .

} 

因此,您有一个“请求”对象,您将其传递到具有字段 siteName 和 methodId 的 WCF 服务。在我提供的示例中,methodId 现在是必需的,这将消除“指定”字段。

【讨论】:

  • 对不起,我说的是方法本身的参数。是不是也需要额外的属性?
  • 我在 "int methodId" 之前添加了 "[DataMember(IsRequired = true)]" 并收到以下错误:属性 'DataMember' 在此声明类型上无效。它仅对“属性、索引器、字段”声明有效。
  • 先前回复中提供的示例。
  • 现在我明白了。非常感谢!
猜你喜欢
  • 1970-01-01
  • 2011-10-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-01-13
  • 2016-10-19
  • 1970-01-01
相关资源
最近更新 更多