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:
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?
CodePudding user response:
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.