Клиент WCF получает значение Даты от веб-сервиса Java, где дата, отправленная клиенту в XML:
2010-05-10+14:00
Теперь клиент WCF, получающий эту дату, находится в часовом поясе (+08:00) и когда клиент десериализовывает значение Даты, это преобразовывается в следующее значение DateTime:
09.05.2010 18:00 +08:00
Однако мы хотели бы проигнорировать +14:00, отправляемый от сервера так, чтобы сериализированное значение Даты в клиенте было:
10.05.2010
Обратите внимание, что +14:00 не последователен и может быть +10:00, +11:00 и т.д., таким образом, не возможно использовать преобразования DateTime на стороне клиента для получения желаемого значения даты.
Как это может быть легко достигнуто в WCF?
Заранее спасибо.
Был бы корректное решение WCF этого для реализации IClientMessageFormatter?
Самое чистое решение для меня состояло в том, чтобы реализовать IClientMessageFormatter, как предложено выше. Вот пример:
Код C#
public class ClientMessageFormatter : IClientMessageFormatter
{
IClientMessageFormatter original;
public ClientMessageFormatter(IClientMessageFormatter actual)
{
this.original = actual;
}
public void RemoveTimeZone(XmlNodeList nodeList)
{
if (nodeList != null)
{
foreach (XmlNode node in nodeList)
{
node.InnerText = Regex.Replace(node.InnerText, @"[\+\-]\d\d:\d\d", "");
}
}
}
#region IDispatchMessageFormatter Members
public object DeserializeReply(Message message, object[] parameters)
{
Message newMessage = null;
Message tempMessage;
MessageBuffer buffer;
MemoryStream ms;
XmlDocument doc;
XmlDictionaryReader reader;
XmlReader xr;
XmlWriter xw;
try
{
buffer = message.CreateBufferedCopy(int.MaxValue);
tempMessage = buffer.CreateMessage();
reader = tempMessage.GetReaderAtBodyContents();
if (reader != null)
{
doc = new XmlDocument();
doc.Load(reader);
reader.Close();
if (doc.DocumentElement != null)
{
/* enables switching between responses */
switch (doc.DocumentElement.LocalName)
{
case "sampleRootElement":
RemoveTimeZone(doc.DocumentElement.SelectNodes("childElement1/childElement2"));
break;
}
}
ms = new MemoryStream();
xw = XmlWriter.Create(ms);
doc.Save(xw);
xw.Flush();
xw.Close();
ms.Position = 0;
xr = XmlReader.Create(ms);
newMessage = Message.CreateMessage(message.Version, null, xr);
newMessage.Headers.CopyHeadersFrom(message);
newMessage.Properties.CopyProperties(message.Properties);
}
}
catch (Exception ex)
{
throw ex;
}
return original.DeserializeReply((newMessage != null) ? newMessage : message, parameters);
}
public Message SerializeRequest(MessageVersion messageVersion, object[] parameters)
{
return original.SerializeRequest(messageVersion, parameters);
}
#endregion
}
public class ClientOperationBehavior : IOperationBehavior
{
public void AddBindingParameters(OperationDescription description, BindingParameterCollection bindingParameters)
{
}
public void ApplyClientBehavior(OperationDescription description, ClientOperation proxy)
{
IClientMessageFormatter currentFormatter = proxy.Formatter;
proxy.Formatter = new ClientMessageFormatter(currentFormatter);
}
public void ApplyDispatchBehavior(OperationDescription description, DispatchOperation operation)
{
}
public void Validate(OperationDescription description)
{
}
}
public class ClientEndpointBehavior : IEndpointBehavior
{
#region IEndpointBehavior Members
public void AddBindingParameters(ServiceEndpoint endpoint, BindingParameterCollection bindingParameters)
{
}
public void ApplyClientBehavior(ServiceEndpoint endpoint, ClientRuntime clientRuntime)
{
foreach (OperationDescription operation in endpoint.Contract.Operations)
{
operation.Behaviors.Add(new ClientOperationBehavior());
}
}
public void ApplyDispatchBehavior(ServiceEndpoint endpoint, EndpointDispatcher endpointDispatcher)
{
}
public void Validate(ServiceEndpoint endpoint)
{
}
#endregion
}
public class ClientBehaviorExtensionElement : BehaviorExtensionElement
{
public override Type BehaviorType
{
get
{
return typeof(ClientEndpointBehavior);
}
}
protected override object CreateBehavior()
{
return new ClientEndpointBehavior();
}
}
App.config/Web.config
Клиентский конфигурационный файл затем использовал бы вышеупомянутое средство форматирования следующим образом:
....
....
....
....
Ссылки
Попробовать
DateTime newDate = DateTime.SpecifyKind(oldDate, DateTimeKind.Unspecified);
Лучшие практики кодирования с использованием DateTime в .NET Framework
Ссылки по теме
http://daveonsoftware.blogspot.com/2008/07/wcf-datetime -field-adjust.html
http://social.msdn.microsoft.com/forums/en-US/wcf/thread/36ae825a-ffc6-4ac3-9981-c82692039d58