我们的要求之一是拥有一个解耦的体系结构,在该体系中,我们需要将数据从一个系统映射到另一个系统,并且中间映射由ServiceStack服务请求处理。我们的问题是供应商只能通过Xml提供的数据不符合ServiceStack提供的标准字典请求,如下所示:
<Lead xmlns:d2p1="http://schemas.microsoft.com/2003/10/Serialization/Arrays">
<d2p1:KeyValueOfstringstring>
<d2p1:Key>String</d2p1:Key>
<d2p1:Value>String</d2p1:Value>
</d2p1:KeyValueOfstringstring>
</Lead>
相反,他们需要一种机制,例如:
<Lead>
<LeadId>Value</LeadId>
<FirstName>First Name</FirstName>
<LastName>Last Name</LastName>
...
</Lead>
由于xml请求中的节点可能会随时间变化,而我们只是充当中间人,是否有一种本机的方式来接受动态请求或将其作为Dictionary处理,其数据类似于以下内容?
Dictionary<string, string>
{
{ "LeadId", "Value" },
{ "FirstName", "First Name" },
{ "LastName", "Last Name" }
...
};
默认的XML序列化没有提供任何可以透明地将XML片段推断为字符串字典的方式,因此您将需要通过告诉ServiceStack跳过内置的序列化来手动解析XML(可以在ServieStack中完成)。实现IRequiresRequestStream
哪个ServiceStack将随请求流一起注入,以便您可以自己反序列化它,例如:
public class Lead : IRequiresRequestStream
{
public Stream RequestStream { get; set; }
}
然后,在您的服务中,您将手动解析原始XML,并将其转换为所需的数据集合,例如:
public class RawServices : Service
{
public object Any(Lead request)
{
var xml = request.RequestStream.ReadFully().FromUtf8Bytes();
var map = new Dictionary<string, string>();
var rootEl = (XElement)XDocument.Parse(xml).FirstNode;
foreach (var node in rootEl.Nodes())
{
var el = node as XElement;
if (el == null) continue;
map[el.Name.LocalName] = el.Value;
}
return new LeadResponse {
Results = map
}
}
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句