简体   繁体   English

使用WCF设置nillable = false

[英]setting nillable=false with WCF

Is it possible to change the default value of nillable on strings to false in the wsdl using WCF? 是否可以使用WCF在wsdl中将字符串上的nilable的默认值更改为false? I can't find any attributes or settings doing this out of the box, but is it possible to extend WCF in some way by using attributes to do this myself? 我找不到开箱即用的任何属性或设置,但是是否可以通过使用属性来自己扩展WCF呢? Or is there a better way around? 还是有更好的方法? I need the possibility mark some of my string properties as nillable=false, but not all. 我需要将某些字符串属性标记为nillable = false,但不是全部。

eg: 例如:

[DataMember]
[Nillable(false)]
public string MyData{ get; set; }
[DataMember(IsRequired=True)]

我相信应该这样做吗?

You have to write your own WsdlExportExtension to achieve this. 您必须编写自己的WsdlExportExtension以实现此目的。

Here's a sample: 这是一个示例:

public class WsdlExportBehavior : Attribute, IContractBehavior, IWsdlExportExtension
{
    public void ExportContract(WsdlExporter exporter, WsdlContractConversionContext context)
    { }

    public void ExportEndpoint(WsdlExporter exporter, WsdlEndpointConversionContext context)
    {
        var schemaSet = exporter.GeneratedXmlSchemas;

        foreach (var value in schemaSet.GlobalElements.Values)
        {
            MakeNotNillable(value);
        }

        foreach (var value in schemaSet.GlobalTypes.Values)
        {
            var complexType = value as XmlSchemaComplexType;
            if (complexType != null && complexType.ContentTypeParticle is XmlSchemaSequence)
            {
                var sequence = complexType.ContentTypeParticle as XmlSchemaSequence;
                foreach (var item in sequence.Items)
                {
                    MakeNotNillable(item);
                }
            }
        }
    }

    private static void MakeNotNillable(object item)
    {
        var element = item as XmlSchemaElement;
        if (element != null)
        {
            element.IsNillable = false;
        }
    }

    public void AddBindingParameters(ContractDescription description, ServiceEndpoint endpoint, BindingParameterCollection parameters)
    { }

    public void ApplyClientBehavior(ContractDescription description, ServiceEndpoint endpoint, ClientRuntime client)
    { }

    public void ApplyDispatchBehavior(ContractDescription description, ServiceEndpoint endpoint, DispatchRuntime dispatch)
    { }

    public void Validate(ContractDescription description, ServiceEndpoint endpoint)
    { }
}

And apply the [WsdlExportBehavior] to your service class. 并将[WsdlExportBehavior]应用于您的服务类。

Hope this helps. 希望这可以帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM