1

I have an .NET 6 API endpoint that needs to be able to take any valid json, and then log it.

The endpoint is post, and I need to be able to send the data in the body.

My idea for doing this, was the following:

    public async Task<IActionResult> LogSomeJSONendpoint([FromBody] JObject payload)
    {
        Log.information(payload));
    }

The logging converts the JObject to a string and then logs it.

but, I call this endpoint, give it the following json:

{"name":"John", "age":30, "car":null}

Then I get this response:

{
    "title": "One or more validation errors occurred.",
    "status": 400,
    "errors": {
        "$.name": [
            "The JSON value could not be converted to Newtonsoft.Json.Linq.JToken. Path: $.name | LineNumber: 0 | BytePositionInLine: 14."
        ]
    }
}

hmmm, what? I'm fairly sure what I posted was valid JSON, so I can't figure out why it can't take it.

If JObject does'nt work for this task, how else could I solve it? I just need to take any valid JSON, turn it into a string, and then log it

penstiaGarse
  • 161
  • 7
  • What version of asp.net / asp.net-core are you using? Is your version using Json.NET or System.Text.Json? If System.Text.Json then `JObject` is not supported out of the box and you will need to use [`JsonElement`](https://docs.microsoft.com/en-us/dotnet/api/system.text.json.jsonelement) or [`JsonObject`](https://docs.microsoft.com/en-us/dotnet/api/system.text.json.nodes.jsonobject). Alternatively, you could revert back to Json.NET by following the instructions from [Where did IMvcBuilder AddJsonOptions go in .Net Core 3.0?](https://stackoverflow.com/a/55666898/3744182). – dbc Jan 25 '23 at 14:49
  • I now tried with JSonobject, but it will not serialize to a string, and JSonElement does serialize into the json I am giving it – penstiaGarse Jan 25 '23 at 14:53
  • Why not take a `string`, validate it parses as JSON, then log it (or return an error response if it does not)? Having the API do the validation by whatever voodoo logic it prefers is only nice until it isn't, as you've found out. – Jeroen Mostert Jan 25 '23 at 17:43
  • @penstiaGarse Try just Log.information(payload.ToString()); – Serge Jan 25 '23 at 17:44

0 Answers0