I'm using https://github.com/odata/ODataConnectedService to communicate with a Business Central server. Everything is working fine. However, I would really like to be able to log the JSON messages sending (and receiving) from the BC server.
Does anybody know how to get the JSON string being send back and forth?
I found out that the generated DataServiceContext
has an event called ReceivingResponse
.
This is my LogReceivingResponse
(not pretty, but it works):
public void LogReceivingResponse(object? sender, ReceivingResponseEventArgs e)
{
try
{
if (e.ResponseMessage is not HttpWebResponseMessage responseMessage)
{
return;
}
var stream = responseMessage.GetStream();
var msInput = new MemoryStream();
stream.CopyTo(msInput);
msInput.Seek(0, SeekOrigin.Begin);
var str = new StreamReader(msInput);
var line = str.ReadToEnd();
line = JsonPrettify(line);
var uri = responseMessage.Response.ResponseUri;
Logger.Debug($"Request: {uri}\nResponse: {line}");
msInput.Seek(0, SeekOrigin.Begin);
Func<Stream> func = () => msInput;
responseMessage.GetType().InvokeMember("getResponseStream",
BindingFlags.SetField | BindingFlags.Instance | BindingFlags.NonPublic, null, responseMessage,
new object[] { func });
}
catch (Exception ex)
{
Logger.Error(ex, "Failed to log receiving response");
}
}
I suspect you can do something similar with the event BuildingRequest
for sending data.