[英]Hook OData's $metadata response and convert it from XML to JSON
The answer of Get OData $metadata in JSON format states that OData cannot return the metadata as JSON by default. Get OData $metadata in JSON format的回答指出 OData 默认不能以 JSON 形式返回元数据。
But is it possible then to capture or hook its response for the $metadata
URL, and then convert it on the fly to JSON before sending it to the client?但是,是否有可能捕获或挂钩其对$metadata
URL 的响应,然后在将其发送到客户端之前将其动态转换为 JSON?
I imagine pseudocode like this:我想像这样的伪代码:
[HttpGet]
[ODataRoute("$metadata")]
public string GetMetadataAsJson()
{
string xml = GetOdataMetadataAsXML();
string json = ConvertToJson(xml);
return json;
}
I don't know how to implement it correctly, though, in particular I'm not sure how to get the standard OData response as a string, and how to hook the $metadata
URL.但是,我不知道如何正确实现它,特别是我不确定如何将标准 OData 响应作为字符串获取,以及如何挂钩$metadata
URL。
Newtonsoft supports the Json part checkout https://www.newtonsoft.com/json/help/html/ConvertXmlToJson.htm Newtonsoft 支持 Json 部分结帐https://www.newtonsoft.com/json/help/html/ConvertXmlToJson.htm
So the actual solution for the Json Part would be quite simple, as soon as you have your XML所以 Json 部分的实际解决方案将非常简单,只要你有你的 XML
[HttpGet]
[ODataRoute("$metadata")]
public string GetMetadataAsJson()
{
string xml = GetOdataMetadataAsXML();
XmlDocument doc = new XmlDocument();
doc.LoadXml(xml);
string json = JsonConvert.SerializeXmlNode(doc);
return json;
}
Also you should probably first check if eg a format query is set for example with this code此外,您可能应该首先检查例如是否使用此代码设置了格式查询
[HttpGet]
[ODataRoute("$metadata")]
public string GetMetadataAsJson([FromQuery(Name="Format")]string format)
{
string metaResult = GetOdataMetadataAsXML();
if(format.Equals("json",StringComparison.OrdinalIgnoreCase))
{
XmlDocument metaDoc = new XmlDocument();
doc.LoadXml(metaResult);
metaResult = JsonConvert.SerializeXmlNode(doc);
}
return metaResult;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.