Reputation: 13
I need to get the request body after exception in my ExceptionHandlingMiddleware
. Before Exception I get easy request body, but after I can't.
Part of code from ExceptionHandlingMiddleware
below.
try
{
await _next.Invoke(context);
}
catch (Exception exception)
{
RequestBody = await FormatRequest(context.Request);
}
private async Task<string> FormatRequest(HttpRequest request)
{
request.EnableBuffering();
var body = request.Body;
var buffer = new byte[Convert.ToInt32(request.ContentLength)];
await request.Body.ReadAsync(buffer, 0, buffer.Length);
var bodyAsText = Encoding.UTF8.GetString(buffer);
return $"{request.Scheme} {request.Host}{request.Path} {request.QueryString}
{bodyAsText}";
}
In result, I get this
I tried to get the body in try
by this way
try
{
RequestBody = await FormatRequest(context.Request);
await _next.Invoke(context);
}
And it works, I get normal json
data, but I have the exception that my model is not valid because it is empty.
I tried to do request.EnableBuffering();
before exception but it didn't help me.
So If I try to get body after exception, I can`t parse it. If I get it before exception my model in the controller is not valid.
How I can get my model after exception for logging in ExceptionHandlingMiddleware
?
Upvotes: 1
Views: 3177
Reputation: 36575
Usually Request.Body
does not support rewinding, so it can only be read once. A temp workaround is to pull out the body right after the call to EnableBuffering
and then rewinding the stream to 0 and not disposing it:
request.EnableBuffering();
var body = request.Body;
var buffer = new byte[Convert.ToInt32(request.ContentLength)];
await request.Body.ReadAsync(buffer, 0, buffer.Length);
var bodyAsText = Encoding.UTF8.GetString(buffer);
request.Body.Position = 0; //rewinding the stream to 0
Upvotes: 3