Convert response body from XML to Json in API Management Policy Expression when forwarding response to different URL

柔情痞子 提交于 2019-12-14 03:05:46

问题


How can I change the response body from XML to Json when forwarding the response to a different URL?

I'm specifically forwarding the response to Azure Service Bus.

I've tried many different ways to serialize XML to json but with no luck because of the restrictions of some JsonConvert methods that's not allowed in policy expressions.

And no, <json-to-xml apply="content-type-json" consider-accept-header="true" /> is not the solution :)

<outbound>
    <base />
        <send-request mode="new" response-variable-name="response_body" timeout="60" ignore-error="true">
            <set-url>https://servicebus.fake</set-url>
            <set-method>POST</set-method>
            <set-header name="Authorization" exists-action="override">
                <value>@{

                  // some code to construct the token key that's needed for service bus requests.

                  }
                </value>
            <set-header name="MessageId" exists-action="skip">
                <value>@{
                  var guid = Guid.NewGuid().ToString();
                  return guid;
                  }
                </value>
            </set-header>
            <set-header name="Content-Type" exists-action="override">
                <value>application/json</value>
            </set-header>
                <set-body>@{

                        // What must I add here?
                }
                </set-body>
       </send-request>
       <set-header name="Content-Type" exists-action="override">
            <value>application/json</value>
        </set-header>
    </outbound>

回答1:


Here's the solution :) The typical JsonConvert.SerializeXmlNode method isn't allowed in policy expressions.

However good ol' JsonConvert.SerializeObject did the trick.

<send-one-way-request mode="new">
    <set-url>http://requestb.in/xje199xj</set-url>
    <set-method>POST</set-method>
    <set-header name="Content-Type" exists-action="override">
    <value>application/json</value>
    </set-header>
        <set-body>@{
            string xml = context.Response.Body.As<string>(preserveContent: true);
            XmlDocument doc = new XmlDocument();
            doc.LoadXml(xml);

            return JsonConvert.SerializeObject(doc);
            }
        </set-body>
</send-one-way-request>


来源:https://stackoverflow.com/questions/57993190/convert-response-body-from-xml-to-json-in-api-management-policy-expression-when

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!