0

I just hit post call and i have request and response both. I have method in which i am trying to log request and repose body in my db for that i am just building req and response body.

internal static async Task<string> GetBodyForLoggingAsync(this HttpRequestMessage request)
{
    return await GetBodyForLoggingAsync(request.Content);
}

private static async Task<string> GetBodyForLoggingAsync(HttpContent content)
{
    if (content == null)
    {
        return null;
    }

    string requestBody = null;

    var contentType = content.Headers.ContentType;

    if (contentType == null || _contentTypesWhereBodyIsLogged.Contains(contentType.MediaType))
    {
        try
        {

            Debug.WriteLine(" ---- GETTING BODY CONTENT");

            using (var ms = new MemoryStream())
            {
                try
                {
                    await content.CopyToAsync(ms).ConfigureAwait(false);
                    ms.Seek(0, SeekOrigin.Begin);
                    using (var sr = new StreamReader(ms))
                    {
                        requestBody = sr.ReadToEnd();
                    }
                }
                catch (Exception ex)
                {
                    var test = ex;
                }
            }
        }
        catch (Exception ex)
        {
            var test = ex;
        }
    }
}

I am getting error of cannot access disposed object in content.CopyToAsync() method for POST and PATCH call and if i do same call from postman making it get i am not getting this error. I know there is no use of body in get call but just i was checking.

Johnathan Barclay
  • 18,599
  • 1
  • 22
  • 35
akash
  • 35
  • 1
  • 6
  • It's hard to tell the context that you're dealing with the HttpContent in can you post the stack trace? If I had to guess, your logging is occurring after the framework has disposed of the request and response. If that's the case you want to move your middleware further up the pipeline. – Timothy Jannace Sep 03 '20 at 12:47
  • Response it getting logged it happens incase of request only. – akash Sep 03 '20 at 14:10
  • Probably duplicate of these questions: https://stackoverflow.com/questions/40494913/how-to-read-request-body-in-a-asp-net-core-webapi-controller https://stackoverflow.com/questions/12494067/read-httpcontent-in-webapi-controller – Timothy Jannace Sep 03 '20 at 14:23
  • No my code throws error when i try to do Copy or Read anything with the error of disposed object. – akash Sep 03 '20 at 14:27
  • Any update on this? – AutomationNerd Sep 23 '20 at 14:47

0 Answers0