0

我有一个 WCF 服务并且不能使用 DataContracts,因为我需要对接收和发送到该服务的 XML 进行更多控制。因此,我使用 XmlRoot 和 XmlElement ...我现在遇到的问题是接收 xml 被反序列化到的类和序列化响应都需要具有相同的根名称,并且当我尝试设置这两个类都具有:

[XmlRoot(ElementName = "myRoot")] 

我收到一条错误消息,指出根名称已被使用。有一个简单的解决方法吗?我尝试将我的响应类放在一个单独的命名空间中,但这似乎不起作用。

如果某些变量未在我的响应类中设置并被序列化,那么我不会将它们序列化并在响应中返回......是否有一个选项我错过了这样做......我能够使用 DataContract 执行此操作,但无法使用 XmlElements 解决此问题

4

1 回答 1

0

实现此目的的一种方法是拦截 XML 响应并将根元素名称更改为唯一的名称,然后再对其进行反序列化。这可以通过自定义 IClientMessageFormatter 和操作上的关联属性轻松完成。

我刚刚写了这个,所以“湿油漆”等等,但看起来是这样的:

/// <summary>
/// An operation attribute that changes the XML root name in responses
/// </summary>
/// <example>
///     
/// [ServiceContract]
/// [XmlSerializerFormat]
/// public interface IRedBlueServiceApi
/// {
///     [OperationContract]
///     [WebGet(...)]
///     [XmlChangeRoot("RedResponse")]
///     RedResponse GetRed();
///
///     [OperationContract]
///     [WebGet(...)]
///     [XmlChangeRoot("BlueResponse")]
///     BlueResponse GetBlue();
/// }
/// 
/// [XmlRoot("RedResponse")]
/// public class RedResponse 
/// {...}
/// 
/// [XmlRoot("BlueResponse")]
/// public class BlueResponse 
/// {...}
/// </example>
[DefaultProperty("NewRootElementName")]
public class XmlChangeRootAttribute : Attribute, IOperationBehavior
{
    public XmlChangeRootAttribute(string newRootElementName)
    {
        NewRootElementName = newRootElementName;
    }

    public string NewRootElementName { get; set; }

    #region IOperationBehavior Members

    public void ApplyClientBehavior(OperationDescription operationDescription, ClientOperation clientOperation)
    {
        // Inject our xml root changer into the client request/response pipeline
        clientOperation.Formatter = new XmlRootChangeFormatter(clientOperation.Formatter, NewRootElementName);
    }

    #endregion

    #region Unrelated Overrides

    public void ApplyDispatchBehavior(OperationDescription operationDescription, DispatchOperation dispatchOperation)
    {
    }

    public void AddBindingParameters(OperationDescription operationDescription,
                                     BindingParameterCollection bindingParameters)
    {
    }

    public void Validate(OperationDescription operationDescription)
    {
    }

    #endregion
}

/// <summary>
/// A simple wrapper around an existing IClientMessageFormatter
/// that alters the XML root name before passing it along
/// </summary>
public class XmlRootChangeFormatter : IClientMessageFormatter
{
    private readonly IClientMessageFormatter _innerFormatter;
    private readonly string _newRootElementName;

    public XmlRootChangeFormatter(IClientMessageFormatter innerFormatter, string newRootElementName)
    {
        if (innerFormatter == null)
            throw new ArgumentNullException("innerFormatter");

        if (String.IsNullOrEmpty(newRootElementName))
            throw new ArgumentException("newRootElementName is null or empty");

        _innerFormatter = innerFormatter;
        _newRootElementName = newRootElementName;
    }

    #region IClientMessageFormatter Members

    public Message SerializeRequest(MessageVersion messageVersion, object[] parameters)
    {
        return _innerFormatter.SerializeRequest(messageVersion, parameters);
    }

    public object DeserializeReply(Message message, object[] parameters)
    {
        if (!message.IsEmpty)
        {
            var doc = XDocument.Load(message.GetReaderAtBodyContents());

            if (doc.Root == null)
                throw new SerializationException("Could not find root in WCF messasge " + message);

            // Change the root element name 
            doc.Root.Name = _newRootElementName;

            // Create a new 'duplicate' message with the modified XML
            var modifiedReply = Message.CreateMessage(message.Version, null, doc.CreateReader());
            modifiedReply.Headers.CopyHeadersFrom(message.Headers);
            modifiedReply.Properties.CopyProperties(message.Properties);

            message = modifiedReply;
        }

        return _innerFormatter.DeserializeReply(message, parameters);
    }

    #endregion
}
于 2010-07-28T16:51:14.527 回答