首页 > 解决方案 > 使用 Flurl.Http,有没有办法确定发送的字节数?

问题描述

我想知道使用 Post 或 PostAsync 时实际传输了多少字节。我正在使用类似于以下的代码。我可以查看 filePath 的字节,但在我的真实代码中,我在读取和发送之间对文件流进行了一些操作。如果你拔MyFilteredContent线,你会怎么做?

async Task<bool> SendFile(string filePath)
{
    using (HttpContent fileContent = new FileContent(filePath))
    using (MyFilteredContent filteredContent = new MyFilteredContent(fileContent))
    {
        var t = await MyAppSettings.TargetUrl
        .AllowAnyHttpStatus()
        .PostAsync(filteredContent);

        if (t.IsSuccessStatusCode)
        {
            return true;
        }

        throw new Exception("blah blah");
    }
}

标签: c#flurl

解决方案


这是我在评论中描述的代码示例 - 使用 DelegatingHandler,覆盖 SendAsync 以获取正在发送的请求的字节,然后配置 FlurlHttp 设置以使用处理程序:

public class HttpFactory : DefaultHttpClientFactory
{
    public override HttpMessageHandler CreateMessageHandler()
    {
        return new CustomMessageHandler();
    }
}

public class CustomMessageHandler : DelegatingHandler
{
    protected async override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
    {
        var content = await request.Content.ReadAsByteArrayAsync();


        return await base.SendAsync(request, cancellationToken);
    }
}

 FlurlHttp.Configure(settings =>
 {
     settings.HttpClientFactory = new HttpFactory();
 });

推荐阅读