在 Azure API 管理中,如何在将正文传递到后端 URL 之前使用表单数据正文向传入请求添加变量?

问题描述 投票:0回答:1

在 Azure API 管理中,我有一个传入请求传递 multipart/form-data 正文,我想在将其发送到后端 URL 之前向 multipart/form-data 正文添加更多变量。

在 Azure APIM Police 中,我尝试将 context.request.body 反序列化为对象,但没有成功。我还尝试将其放入 Jobject 并返回 JObject.ToString() 但它也不起作用。

我已经能够毫无问题地将项目添加到常规主体中。

azure azure-api-management
1个回答
0
投票

显然请求体的结构比简单的JSON要复杂一些 如果您想在将 multipart/form-data 正文发送到后端 URL 之前向其添加更多变量,则需要操作 context.Request.Body 属性,该属性包含原始请求正文。让我给你一个示例片段。作为 XML

<policies>
    <inbound>
        <base />
        <set-variable name="newVariable" value="newValue" />
        <set-body>@{
            // Parse the existing multipart/form-data body
            var formData = System.Web.HttpUtility.ParseQueryString(context.Request.Body.As<string>());

            // Add a new variable
            formData.Add("newVariable", context.Variables["newVariable"].ToString());

            // Reconstruct the multipart/form-data body
            var newBody = string.Join("&", formData.AllKeys.Select(key => $"{key}={formData[key]}"));

            return newBody;
        }</set-body>
    </inbound>
    <backend>
        <base />
    </backend>
    <outbound>
        <base />
    </outbound>
    <on-error>
        <base />
    </on-error>
</policies>

© www.soinside.com 2019 - 2024. All rights reserved.