使用 WCF 设置 nillable=false [英] setting nillable=false with WCF

查看:22
本文介绍了使用 WCF 设置 nillable=false的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以使用 WCF 在 wsdl 中将字符串上 nillable 的默认值更改为 false?我找不到任何开箱即用的属性或设置,但是是否可以通过使用属性自己来以某种方式扩展 WCF?或者有更好的方法吗?我需要将我的一些字符串属性标记为 nillable=false,但不是全部.

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.

例如:

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

推荐答案

您必须编写自己的 WsdlExportExtension 才能实现此目的.

You have to write your own WsdlExportExtension to achieve this.

这是一个示例:

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)
    { }
}

并将 [WsdlExportBehavior] 应用到您的服务类.

And apply the [WsdlExportBehavior] to your service class.

希望这会有所帮助.

这篇关于使用 WCF 设置 nillable=false的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆