Capture the size of the response (in bytes) of a WebAPI method call

11,314

Solution 1

Here is a message handler that can get the sizes you are looking for,

public class ResponseSizeHandler : DelegatingHandler
{
    protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
    {

        var response = await base.SendAsync(request, cancellationToken);
        if (response.Content != null)
        {
           await response.Content.LoadIntoBufferAsync();
           var bodylength = response.Content.Headers.ContentLength;
           var headerlength = response.Headers.ToString().Length;
        }
        return response;
    }
}

Just add an instance of this handler as the first message handler.

config.MessageHandlers.Add(new ResponseSizeHandler());

Don't be concerned by the LoadIntoBufferAsync, unless you actually do streaming content then almost all content is buffered by the host anyway, so doing it a little earlier in the pipeline will not add any extra overhead.

Solution 2

You can use Chrome F12 Developer Tools and its Network Tab or Fiddler tool to get the Content-Length of a particular HTTP Response.

In Chrome (for example) -

enter image description here

In Fiddler (for example) -

enter image description here

UPDATE

In Web API you can have a DelegatingHandler to record the response, and in DelegatingHandler you can have like this to get the ContentLength, in face you can get all the headers and response also -

return base.SendAsync(request, cancellationToken).ContinueWith((task) =>
{
        HttpResponseMessage response = task.Result;
        var contentLength = response.Content.Headers.ContentLength;
        return response;
});
Share:
11,314
Jeremy Holovacs
Author by

Jeremy Holovacs

I am a professional geek, involved with multiple facets of software engineering. Security, scalability, performance, and usability are all key factors in all my products.

Updated on June 08, 2022

Comments

  • Jeremy Holovacs
    Jeremy Holovacs almost 2 years

    Is there a way to do this in WebAPI without reinventing the wheel? I can easily get the size of the object returned via WebAPI, but of course there are headers and serialization overhead. Since we are charged by bandwidth utilization, I'd like to know how big our responses are, but there does not seem to be an obvious mechanism for doing so.

    EDIT To be clear, I am looking for a way to do this programatically, so that I can report, analyze, and predict usage, and so I don't get caught by surprise with a bill.