Azure APIM - Set-Variable when optional parameter is missing

juni dev 361 Reputation points
2022-12-15T21:42:03.257+00:00

Hi,

I have this code running fine except when the request omits the "accountEnabled" attribute

this parameter (accountEnabled) is optional. If it is submitted, it must be true, otherwise the request must be rejected
I did it like this:

<inbound>  

    <set-variable name="IsAccounPresent" value="@(context.Request.Body.As<JObject>(true).ContainsKey("accountEnabled"))" />  
    <set-variable name="IsAccountDisabling" value="@(context.Request.Body.As<JObject>(true)["accountEnabled"].Value<bool>() == false)" />  

    <choose>  
        <when condition="@(((bool)context.Variables["IsAccounPresent"]) && ((bool)context.Variables["IsAccountDisabling"]))">  
            <return-response>  
                <set-status code="401" reason="The attribute &apos;accountEnabled&apos; can only be set to true!" />  
            </return-response>  
        </when>  
    </choose>  
    <set-body template="liquid">  
    {  
    ....other attributes removed for clarity  
    {%if  body.accountEnabled %} ,"accountEnabled":"{<!-- -->{body.accountEnabled}}" {% endif %}  
    {%if  body.email %} ,"email":"{<!-- -->{body.email}}" {% endif %}  
    }      
    </set-body>  
    <base />  
</inbound>  

the problem is when the optional attribute (accountEnabled) is not submitted I get this exception:
"expression": "context.Request.Body.As<JObject>(true)[\"accountEnabled\"].Value<bool>() == false",
"details": "Value cannot be null.\r\nParameter name: value\r\n at Newtonsoft.Json.Linq.Extensions.Value[T,U](IEnumerable`1 value)"

If I use this below expression, there is no exception but I do not get the correct value for the condition result
<when condition="@((bool)(context.Request.MatchedParameters.ContainsKey("accountEnabled") && ((bool)(context.Request.Body.As<JObject>(true)["accountEnabled"].Value<bool>() == false))))">

Any suggestion?

Thanks,
JD

Azure API Management
Azure API Management
An Azure service that provides a hybrid, multi-cloud management platform for APIs.
{count} votes

1 answer

Sort by: Most helpful
  1. JananiRamesh-MSFT 29,436 Reputation points Moderator
    2022-12-20T04:20:14.877+00:00

    Hi @juni dev Thanks for reaching out. please find below working policy
      272357-image.png

    Do let me know if you have any queries.

    Please 'Accept as answer' and ‘Upvote’ if it helped so that it can help others in the community looking for help on similar topics.

    0 comments No comments

Your answer

Answers can be marked as 'Accepted' by the question author and 'Recommended' by moderators, which helps users know the answer solved the author's problem.