简体   繁体   中英

setting nillable=false with WCF

Is it possible to change the default value of nillable on strings to false in the wsdl using WCF? 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? Or is there a better way around? I need the possibility mark some of my string properties as nillable=false, but not all.

eg:

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

我相信应该这样做吗?

You have to write your own WsdlExportExtension to achieve this.

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.

Hope this helps.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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