0

I have two C#.NET REST API API1 calling to a legacy API2 with a POST request. With the following simple HTTPClient request where I am sending in a SQL query string and the corresponding parameters inside a MessageRequest object.

string sqlQueryString = "SELECT * FROM TargetTable WHERE Param1 = ? AND Param2=? AND Param3=?";
object[] parameters = new Object[] { "parameter1", "parameter2", "parameter3" };

        var messageRequest = new MessageRequest
        {
            MethodParameters = new Object[] {                       
                    sqlQueryString,
                    parameters
            }
        };


        var response = _httpClient.SendAsync(
            new HttpRequestMessage
            {
                RequestUri = new Uri("api/targetEndpoint", UriKind.Relative),
                Method = HttpMethod.Post,
                Content = new StringContent(JsonSerializer.Serialize(messageRequest, new JsonSerializerOptions
                {
                    IgnoreNullValues = true,

                }), Encoding.UTF8, "application/json")
            }).Result;

But on the API2 when it is received, the System.object[] parameter list, somehow get converted to Newtonsoft.Json.Linq.JArray, and is rejected on the API2. API2 being a legacy code can't be updated to accept jArray at this point.

And when I POST to the same endpoint in API2 with Postman with the following body, it works fine and stays as a System.Object[]:

"MethodParameters": [
    ""SELECT * FROM TargetTable WHERE Param1 = ? AND Param2=? AND Param3=?",
    {
        "$type": "System.Object[]",
        "$values": ["parameter1", "parameter2", "parameter3"]
    }
],

Is there a way to stop the conversion to JArray and maintain the parameters as an object[] thought the transaction?

Gama Sharma
  • 51
  • 1
  • 7
  • 1
    *somehow* has an answer. API2 is deserializing to that type. Can you show us the code that is deserializing your `object[] parameters` ? Can't really answer anything without it. – James Gould Apr 14 '22 at 20:21
  • 1
    `"$type"` is a property specific to Json.NET that conveys type information; see [TypeNameHandling setting](https://www.newtonsoft.com/json/help/html/serializetypenamehandling.htm). But you are using System.Text.Json which does not support $type, see [TypeNameHandling.All not supported](https://docs.microsoft.com/en-us/dotnet/standard/serialization/system-text-json-migrate-from-newtonsoft-how-to#typenamehandlingall-not-supported). If you want to generate $type properties you must switch back to Json.NET. Without the `"$type": "System.Object[]"` property the server deserializes to `JArray`. – dbc Apr 14 '22 at 22:34
  • But for security reasons you might want to change your design to avoid TypeNameHandling, see [TypeNameHandling caution in Newtonsoft Json](https://stackoverflow.com/q/39565954/3744182) for why. – dbc Apr 14 '22 at 22:36

0 Answers0