jeudi 4 mai 2017

Should my logging code create a copy of HttpWebResponse so the stream isn't closed for later use?

I am wanting to log all responses and requests that happen through my application. I have a custom WebClient object that I am logging the requests.

I have a function such as below that takes a request and response object and writes the contents to file:

public string GetFileContents(HttpWebRequest request, HttpWebResponse response)
{
    string requestBody = null;
    string responseBody = null;
    if ( request.Method == WebRequestMethods.Http.Get )
    {
        requestBody = String.Empty;
    } else
    {
        using (StreamReader streamReader = new StreamReader(request.GetRequestStream()))
        {
            requestBody = streamReader.ReadToEnd();
        }
    }

    using (StreamReader streamReader = new StreamReader(response.GetResponseStream()))
    {
        responseBody = streamReader.ReadToEnd();
    }

The issue I am having is that after I LogRequest(webRequest, httpWebResponse); in my application, I am then later on reading that response in a function called CreateHttpResponseData(httpWebResponse);.

I am receiving an exception Stream was not readable which I think is because my logging function is closing the stream.

What is the correct way to get around this? In my logging function as above, should I not close it and allow the calling code to manage that (as I am just logging it)?




Aucun commentaire:

Enregistrer un commentaire