Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Persist formatting of original document with JsonDocument

Environment .net 6 minimal api

app.MapPost("/HandleStatusUpdate", async (System.Text.Json.JsonDocument jsonBody, [FromServices] IMediator mediator, Microsoft.AspNetCore.Http.HttpContext context) =>

I’m accepting webhook requests from a variety of sources and need to validate the message against a static key (static key + message = request header sha value) that I have from each service sending the request.

The issue I am having is that, when I convert the JsonDocument to string:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

 using (var stream = new MemoryStream())
        {
            var writer = new Utf8JsonWriter(stream);
            jdoc.WriteTo(writer);
            writer.Flush();
            return Encoding.UTF8.GetString(stream.ToArray());
        }

it’s not re-creating the exact message that was sent (it removes spaces) so the verification step is failing. I’ve verified that if I take the original message sent and run it through the verification step that it DOES validate.

It is a JSON string being sent with content type of application/json. Since, I am accepting things from a variety of sources, I cant create a class that I can Serialize to.

I don’t think there’s a way I can tell the JsonDocument to persist the formatting of the Json document coming in, so is there a better way to handle this?

>Solution :

You may use JsonDocument.RootElement.GetRawText() to get the original JSON with the original formatting. From the docs:

JsonElement.GetRawText Method

Gets a string that represents the original input data backing this value.

Thus, you may just do:

return jdoc.RootElement.GetRawText();

Demo fiddle here.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading