如何在 WCF 中将有限值设置为 maxoccurrs 而不是“无界”

2023-12-08

我有 WCF 服务。当我公开我的服务时,我的所有数据契约都将转换为元素,并且每个带有 ComplextType 标记的元素也会转换为“ArrayOf”。在 ComplextType 标记中, maxOccurs 的默认值为“无界”。

但实际上我想覆盖这个 maxOccurs 值并为生成的 XSD 文件中“ArrayOf”内的每个元素设置一个有限值(例如:maxOccurs =“10”)。

我尝试实现 IXMLSerialized,但没有成功。有人可以帮我穿上这个吗?

Note:服务和数据契约的命名空间是不同的

我的服务合同:

[ServiceContract]
public interface IMyService
{
    [OperationContract]
    [FaultContract(typeof(ServiceApplicationFault), Action = ServiceApplicationFault.FaultContractAction)]
    EmployeeModel GetDetails(String EmpId);
}

我的数据合同

[DataContract]
public class EmployeeModel
{
    [DataMember]
    public string EmpId { get; set; }

    [DataMember]
    public string EmpName { get; set; }

    [DataMember]
    public string EmpDept { get; set; }

}

我生成的 XSD

<xs:complexType name="ArrayOfEmployeeModel">
<xs:sequence>
<xs:element minOccurs="0" maxOccurs="unbounded" name="EmployeeModel" nillable="true" type="tns:EmployeeModel"/>
</xs:sequence>
</xs:complexType>
<xs:element name="ArrayOfEmployeeModel" nillable="true" type="tns:ArrayOfEmployeeModel"/>
<xs:complexType name="EmployeeModel">
<xs:sequence>
<xs:element minOccurs="0" name="EmpId" nillable="true" type="xs:string"/>
<xs:element minOccurs="0" name="EmpName" nillable="true" type="xs:string"/>
<xs:element minOccurs="0" name="EmpDept" nillable="true" type="xs:string"/>
</xs:sequence>
</xs:complexType>
<xs:element name="EmployeeModel" nillable="true" type="tns:EmployeeModel"/>

经过长时间的研究,我找到了我的问题的解决方案。我们可以通过重写生成的 XSD 模式来做到这一点。可以通过实现来重写此模式IContractBehavior、IWsdlExportExtension接口。

步骤1:创建一个名称带有后缀“Attribute”的类,并为该类实现Attribute类和IContractBehavior、IWsdlExportExtension。

步骤 2:将此类作为属性添加到您的服务契约中。

步骤3:现在在方法 IWsdlExportExtension.ExportEndpoint(WsdlExporter exporter, WsdlEndpointConversionContext context) 中实现您的要求。此时您将获得可用的元数据信息。

欲了解更多信息,请参阅here and here

感谢大家!

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何在 WCF 中将有限值设置为 maxoccurrs 而不是“无界” 的相关文章

随机推荐