I’m trying to read the request body with the code below with Net Core, but I’m getting an error.
Error: Cannot access a disposed object.
Object name: ‘HttpRequestStream’.
private async Task<string> GetRequestBody(HttpRequest request)
{
request.EnableBuffering();
request.Body.Position = 0;
using var reader = new StreamReader(request.Body, leaveOpen: true);
var body = await reader.ReadToEndAsync();
request.Body.Position = 0;
return body;
}
public void Initialize(ITelemetry telemetry)
{
try
{
if (telemetry == null)
return;
if (telemetry is RequestTelemetry requestTelemetry)
{
var httpContext = _httpContextAccessor.HttpContext;
if (httpContext == null || httpContext.Request == null)
return;
var request = httpContext.Request;
if (request.Method == HttpMethod.Post.Method ||
request.Method == HttpMethod.Put.Method ||
request.Method == "PATCH")
{
requestTelemetry.Properties.Add(_requestBody, GetRequestBody(request).Result);
requestTelemetry.Properties.Add(_requestHeaders, GetRequestHeaders(request));
}
}
}
catch
{
}
}