【发布时间】:2020-09-29 15:23:05
【问题描述】:
背景信息
我有两个 .net 服务(比如 A 和 B)。服务 B 使用服务 A 的服务引用。这里使用的是“basicHttpBinding”。
服务 A 中有一个 global.asax.cs,我计划在将调用发送到服务 A.svc.cs 之前执行一些操作
我可以使用以下代码读取 global.asax.cs 中的请求正文。
StreamReader streamReader = new StreamReader(HttpContext.Current.Request.InputStream);
streamReader.BaseStream.Position = 0;
string message = streamReader.ReadToEnd();
“消息”字符串变量保存请求正文,即 xml 格式的有效负载。我可以使用以下代码读取 xml。
XmlDocument doc = new XmlDocument();
doc.LoadXml(message);
xml 看起来像这样
<?xml version="1.0" encoding="UTF-8"?>
<s:Envelope xmlns:s="http://schemas.xmlsoap.org/soap/envelope/">
<s:Body>
<FunctionName xmlns="http://tempuri.org/">
<sampleString>value</sampleString>
<sampleObject xmlns:a="http://schemas.datacontract.org/2004/07/contract" xmlns:i="http://www.w3.org/2001/XMLSchema-instance">
<a:sampleProperty1>value1</a:sampleProperty1>
<a:sampleProperty2>value2</a:sampleProperty2>
</sampleObject>
</FunctionName>
</s:Body>
</s:Envelope>
问题
有没有办法把这个xml转换成json?我只对xml里面的数据感兴趣。
奖金问题
“a:sampleProperty”中的“a:”是什么意思/代表什么?
期望的输出
最终的json应该是这样的
{
"sampleString": "value",
"sampleObject": {
"sampleProperty1": "value1",
"sampleProperty2": "value2"
}
}
我尝试过的事情
我尝试使用代码删除顶级父节点及其属性。然后,我用 JsonConvert 将 xml 转换为 json
JsonConvert.SerializeXmlNode(doc.ChildNodes[0].ChildNodes[0].ChildNodes[0], Newtonsoft.Json.Formatting.None, true);
这样做只对我有部分帮助,我以以下 json 输出结束
{
"sampleString": "value",
"sampleObject": {
"@xmlns:a":"http://schemas.datacontract.org/2004/07/contract",
"@xmlns:i":"http://www.w3.org/2001/XMLSchema-instance",
"a:sampleProperty1": "value1",
"a:sampleProperty2": "value2"
}
}
【问题讨论】:
-
我也有同样的问题
-
有什么理由不能从服务返回 JSON 吗? stackoverflow.com/questions/11088294/…
-
@SiddheshKulkarni - 检查我的回答是否对您的查询也有帮助!