user610217
user610217

Reputation:

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

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.

Upvotes: 6

Views: 17315

Answers (2)

Darrel Miller
Darrel Miller

Reputation: 142174

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.

Upvotes: 23

ramiramilu
ramiramilu

Reputation: 17182

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;
});

Upvotes: 1

Related Questions