簡體   English   中英

將響應轉發到其他URL時,將響應主體從XML轉換為API管理策略表達式中的Json

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

將響應轉發到其他URL時,如何將響應主體從XML更改為Json?

我專門將響應轉發到Azure Service Bus。

我嘗試了許多不同的方法將XML序列化為json,但是由於策略表達式中不允許使用的某些JsonConvert方法的限制,所以運氣不佳。

不, <json-to-xml apply="content-type-json" consider-accept-header="true" />不是解決方案:)

<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>

這是解決方案:)策略表達式中不允許使用典型的JsonConvert.SerializeXmlNode方法。

然而,出色的JsonConvert.SerializeObject可以解決問題。

<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>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM