Loudenvier
Loudenvier

Reputation: 8804

Calculating HttpRequestMessage and HttpResponseMessage total length

I've created an ActionFilter to try to control data usage by our API clients so that we can pinpoint misbehaving clients. The action filter is trivial:

[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method)]
public class CollectDeviceDataUsageAttribute : ActionFilterAttribute
{
    public override void OnActionExecuted(HttpActionExecutedContext actionExecutedContext) {
        if (actionExecutedContext.ActionContext.ActionArguments.ContainsKey("id")) {
            long id = (long)actionExecutedContext.ActionContext.ActionArguments["id"];
            var action = actionExecutedContext.ActionContext.ActionDescriptor.ActionName.ToUpper();
            var method = actionExecutedContext.Request.Method.Method;
            var resource = method + " " + action;
            IntegraRepository.CollectDeviceUsage(id.ToString(), resource, actionExecutedContext.Request, actionExecutedContext.Response);
        }
        base.OnActionExecuted(actionExecutedContext);
    }
}

It delegates the data usage calulcation to the CollectDeviceUsage method. The trouble is: I don't know how I can get the actual "byte" size of both the Request and the Response! I can get the Content-Lenght of each, but that won't take into account the Headers. This doesn't need to be a super-ultra-accurate measure of data usage, I'm not interested in TCP/IP overhead, but the HTTP headers overhead I believe is enough to consider.

Here is the code I use to get the cotent-lengh:

var sizeReq = request.Content.Headers.ContentLength ?? 0;
var sizeResp = response == null ? 0 : response.Content.Headers.ContentLength ?? 0;

How could I also collect the actual Headers received/to be sent lenght? Something like request.Content.Headers.Length :-)

UPDATE

It was very simple to get the Request's header's length:

request.Headers.ToString().Length;

The trouble now lies only with the Respone headers. I believe I don't have enough information at the OnActionExecuted method to figure out the Headers that will be sent to the client, as the response.Headers return an empty collection!

Upvotes: 0

Views: 2845

Answers (1)

Mrchief
Mrchief

Reputation: 76238

You'd need a ResultFilter and do your processing in OnResultExecuted method.

You need to ensure that your filter is the last one to run, so make sure you specify Last scope. This would ensure that your filter runs last even if other result filters are present.

You may find this page about filter order and scope helpful (scroll to Filter Order section).

Upvotes: 1

Related Questions