繁体   English   中英

.NET 4.5 XmlSerializer,xsi:nillable属性和字符串值的问题

[英]Problems with .NET 4.5 XmlSerializer, xsi:nillable attribute, and string values

对于StackOverflow的大人物,请听我的请求:

我正在编写.NET 4.5库代码以与Oracle SalesCloud服务进行通信,并且我遇到了在C#对象上具有空字符串值的SOAP请求的问题。

属性的XSD指定如下:

<xsd:element minOccurs="0" name="OneOfTheStringProperties" nillable="true" type="xsd:string" />

使用VS2013中的“添加服务引用...”实用程序并在我正在更新OneOfTheStringProperties之外的其他内容时写入请求,输出为

<OneOfTheStringProperties xsi:nil="true></OneOfTheStringProperties>

在服务器端,这会导致两个问题。 首先,由于也以这种方式指定了只读属性,因此服务器拒绝整个请求。 其次,这意味着我可能无意中消除了我想要保留的值(除非我每次都发回每个属性......效率低下且编码很难。)

我的Google-fu在这一方面很弱,而且我不想深入研究自定义XmlSerializer(以及随之而来的所有测试/边缘情况),除非它是最好的路线。

到目前为止,我能找到的最好的是遵循[Property] Specified模式。 这样做,对于每个可用的字符串属性意味着我必须将以下内容添加到Reference.cs中的定义

[System.Xml.Serialization.XmlIgnoreAttribute()]
public bool OneOfTheStringPropertiesSpecified 
{
    get { return !String.IsNullOrEmpty(OneOfTheStringProperties); }
    set { }
}

这是很多打字,但它的工作原理,SOAP消息的日志跟踪是正确的。

我希望就三种途径之一提供建议:

  1. 配置开关,特定XmlSerializer覆盖或其他一些修复将禁止.NET 4.5 XmlSerializer输出为空字符串

  2. 像“ <OneOfTheStringProperties xsi:nil="true" />那样会产生”正确“XML的相同秘密公式

  3. 有针对性的教程来创建扩展(或现有的VS2013扩展),这将允许我右键单击字符串属性并插入以下模式:

     [System.Xml.Serialization.XmlIgnoreAttribute()] public bool [$StringProperty]Specified { get { return !String.isNullOrEmpty([$StringProperty]); } set { } } 

我也对任何其他建议持开放态度。 如果只是使用正确的搜索条件(显然,我不是),那也将非常感激。

为了促进这一要求,知识的守护者,我提供了这种牺牲的山羊

添加澄清

为了确保,我不是在寻找一键魔术子弹。 作为一名开发人员,尤其是那些在基础结构经常因需求而发生变化的团队中工作的人,我知道要做好准备需要做很多工作。

但是,我正在寻找的是每次我必须对结构进行刷新时合理地减少工作量(对于其他人来说,这是一个简化的配方来实现同样的目的。)例如,使用* Specified意味着输入对于给定的示例,大约165个字符。 对于包含45个字符串字段的合同,这意味着每次模型更改时我必须输入超过7,425个字符 - 这是一个服务对象! 有大约10-20个服务对象可供争夺。

右键单击的想法会将其减少到45次右键单击操作......更好。

放在类上的自定义属性会更好,因为每次刷新只需要完成一次。

理想情况下,app.config中的运行时设置将是一劳永逸的 - 无论第一次实现多么困难,因为它进入库。

我认为真正的答案是比一个近7500个字符/类更好的地方,可能不如简单的app.config设置好,但它要么在那里,要么我相信它可以制作。

这不是完美的解决方案,但沿着45右键单击行,您可以使用T4文本模板在与生成的Web服务代码分离的部分类声明中生成XXXSpecified属性。

然后,单击右键单击 - >运行自定义工具,以在更新服务引用时重新生成XXXSpecified代码。

这是一个示例模板,它为给定命名空间中的类的所有字符串属性生成代码:

<#@ template debug="false" hostspecific="false" language="C#" #>
<#@ assembly name="System.Core" #>
<#@ assembly name="$(SolutionDir)<Path to assembly containing service objects>" #>
<#@ import namespace="System.Linq" #>
<#@ import namespace="System.Text" #>
<#@ import namespace="System.Collections.Generic" #>
<#@ import namespace="System.Reflection" #>
<#@ output extension=".cs" #>

<#
    string serviceObjectNamespace = "<Namespace containing service objects>";
#>

namespace <#= serviceObjectNamespace #> {

<#
        foreach (Type type in AppDomain.CurrentDomain.GetAssemblies()
                       .SelectMany(t => t.GetTypes())
                       .Where(t => t.IsClass && t.Namespace == serviceObjectNamespace)) {

        var properties = type.GetProperties().Where(p => p.PropertyType == typeof(string));
        if (properties.Count() > 0) {
#>

    public partial class <#= type.Name #> {

    <#
        foreach (PropertyInfo prop in properties) {
    #>

        [System.Xml.Serialization.XmlIgnoreAttribute()]
        public bool <#= prop.Name#>Specified 
        {
            get { return <#= prop.Name#> != null; }
            set { }
        }

    <#
        } 
    #>

    }

<#
    } }
#>

}

以下是如何向WCF客户端添加自定义行为,该行为可用于检查消息并跳过属性。

这是以下组合:

完整代码:

void Main()
{
    var endpoint = new Uri("http://somewhere/");

    var behaviours = new List<IEndpointBehavior>()
    {
        new SkipConfiguredPropertiesBehaviour(),
    };

    var channel = Create<IRemoteService>(endpoint, GetBinding(endpoint), behaviours);
    channel.SendData(new Data()
    {
        SendThis = "This should appear in the HTTP request.",
        DoNotSendThis = "This should not appear in the HTTP request.",
    });
}

[ServiceContract]
public interface IRemoteService
{
    [OperationContract]
    int SendData(Data d);
}

public class Data
{
    public string SendThis { get; set; }
    public string DoNotSendThis { get; set; }
}

public class SkipConfiguredPropertiesBehaviour : IEndpointBehavior
{
   public void AddBindingParameters(
        ServiceEndpoint endpoint,
        BindingParameterCollection bindingParameters)
    {
    }

    public void ApplyClientBehavior(
        ServiceEndpoint endpoint, 
        ClientRuntime clientRuntime)
    {
        clientRuntime.MessageInspectors.Add(new SkipConfiguredPropertiesInspector());
    }

    public void ApplyDispatchBehavior(
        ServiceEndpoint endpoint, 
        EndpointDispatcher endpointDispatcher)
    {
    }

    public void Validate(
        ServiceEndpoint endpoint)
    {
    }
}

public class SkipConfiguredPropertiesInspector : IClientMessageInspector
{
    public void AfterReceiveReply(
        ref Message reply, 
        object correlationState)
    {
        Console.WriteLine("Received the following reply: '{0}'", reply.ToString());
    }

    public object BeforeSendRequest(
        ref Message request, 
        IClientChannel channel)
    {     
        Console.WriteLine("Was going to send the following request: '{0}'", request.ToString());

        request = TransformMessage(request);

        return null;
    }

    private Message TransformMessage(Message oldMessage)
    {
        Message newMessage = null;
        MessageBuffer msgbuf = oldMessage.CreateBufferedCopy(int.MaxValue);
        XPathNavigator nav = msgbuf.CreateNavigator();

        //load the old message into xmldocument
        var ms = new MemoryStream();
        using(var xw = XmlWriter.Create(ms))
        {
            nav.WriteSubtree(xw);
            xw.Flush();
            xw.Close();
        }

        ms.Position = 0;
        XDocument xdoc = XDocument.Load(XmlReader.Create(ms));

        //perform transformation
        var elementsToRemove = xdoc.Descendants().Where(d => d.Name.LocalName.Equals("DoNotSendThis")).ToArray();

        foreach(var e in elementsToRemove)
        {
            e.Remove();
        }

        // have a cheeky read...
        StreamReader sr = new StreamReader(ms);
        Console.WriteLine("We're really going to write out: " + xdoc.ToString());

        //create the new message           
        newMessage = Message.CreateMessage(xdoc.CreateReader(), int.MaxValue, oldMessage.Version);

        return newMessage;
    }    
}

 public static T Create<T>(Uri endpoint, Binding binding, List<IEndpointBehavior> behaviors = null)
{
    var factory = new ChannelFactory<T>(binding);

    if (behaviors != null)
    {
        behaviors.ForEach(factory.Endpoint.Behaviors.Add);
    }

    return factory.CreateChannel(new EndpointAddress(endpoint));
}

public static BasicHttpBinding GetBinding(Uri uri)
{
    var binding = new BasicHttpBinding()
    {
        MaxBufferPoolSize = 524288000, // 10MB
        MaxReceivedMessageSize = 524288000,
        MaxBufferSize = 524288000,
        MessageEncoding = WSMessageEncoding.Text,
        TransferMode = TransferMode.Buffered,
        Security = new BasicHttpSecurity()
        {
            Mode = uri.Scheme == "http" ? BasicHttpSecurityMode.None : BasicHttpSecurityMode.Transport,
        }
    };

    return binding;
}

这是LinqPad脚本的链接: http ://share.linqpad.net/kgg8st.linq

如果你运行它,输出将是这样的:

Was going to send the following request: '<s:Envelope xmlns:s="http://schemas.xmlsoap.org/soap/envelope/">
  <s:Header>
    <Action s:mustUnderstand="1" xmlns="http://schemas.microsoft.com/ws/2005/05/addressing/none">http://tempuri.org/IRemoteService/SendData</Action>
  </s:Header>
  <s:Body>
    <SendData xmlns="http://tempuri.org/">
      <d xmlns:d4p1="http://schemas.datacontract.org/2004/07/" xmlns:i="http://www.w3.org/2001/XMLSchema-instance">
        <d4p1:DoNotSendThis>This should not appear in the HTTP request.</d4p1:DoNotSendThis>
        <d4p1:SendThis>This should appear in the HTTP request.</d4p1:SendThis>
      </d>
    </SendData>
  </s:Body>
</s:Envelope>'
We're really going to write out: <s:Envelope xmlns:s="http://schemas.xmlsoap.org/soap/envelope/">
  <s:Header>
    <Action a:mustUnderstand="1" xmlns="http://schemas.microsoft.com/ws/2005/05/addressing/none" xmlns:a="http://schemas.xmlsoap.org/soap/envelope/">http://tempuri.org/IRemoteService/SendData</Action>
  </s:Header>
  <s:Body>
    <SendData xmlns="http://tempuri.org/">
      <d xmlns:a="http://schemas.datacontract.org/2004/07/" xmlns:i="http://www.w3.org/2001/XMLSchema-instance">
        <a:SendThis>This should appear in the HTTP request.</a:SendThis>
      </d>
    </SendData>
  </s:Body>
</s:Envelope>

暂无
暂无

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

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