Search code examples
c#.nethttpwebrequesthttpwebresponse

Detailed timing info from HttpWebRequest


I'm trying to extract detailed timing info, much like the Timing tab in Chrome, from a HTTP request made through HttpWebRequest in .NET:

enter image description here

Anyone know if this is possible? I cannot find any other documentation, than wrapping the entire request in a Stopwatch. But I really want the details, like how long it takes to resolve from DNS, how long it takes to request, content download etc.


Solution

  • For future reference, I'm answering my own question. While the proposed answer with the logger might work, I've found a better (IMO) and much simpler approach:

    var waiting = new Stopwatch();
    var contentDownload = new Stopwatch();
    waiting.Start();
    using (var webResponse = (HttpWebResponse)webRequest.GetResponse())
    {
        waiting.Stop();
        contentDownload.Start();
        using (var reader = new StreamReader(webResponse.GetResponseStream()))
        {
            var body = reader.ReadToEnd();
            contentDownload.Stop();
        }
    }
    

    It's as simple as that really. Calling GetResponse corresponds Chrome's Waiting and GetResponseStream+ReadToEnd corresponds Content Download.

    In this example I'm making a GET (body-less) request. Being able to time Request Sent would make sense, but not really achievable using this approach.