捕获响应的的WebAPI方法调用的大小(以字节为单位) [英] Capture the size of the response (in bytes) of a WebAPI method call

查看:218
本文介绍了捕获响应的的WebAPI方法调用的大小(以字节为单位)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有办法在的WebAPI做到不重新发明轮子?我可以轻松地获得通过的WebAPI返回的对象的大小,但当然也有标题和序列化的开销。因为我们是由带宽利用率收费,我想知道我们的反应有多大,但似乎并没有成为这样一个明显的机制。

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.

推荐答案

下面是一个消息处理程序,可以让你正在寻找的大小,

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



不要被有关 LoadIntoBufferAsync ,除非你其实流媒体内容,然后几乎所有的内容是由主机缓存无论如何,所以做起来早些时候在管道一点都不会增加任何额外的开销。

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.

这篇关于捕获响应的的WebAPI方法调用的大小(以字节为单位)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆