【问题标题】:Using Flurl.Http, is there a way to determine the number of bytes sent?使用 Flurl.Http,有没有办法确定发送的字节数?
【发布时间】:2018-06-13 16:59:02
【问题描述】:

我想知道使用 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");
    }
}

【问题讨论】:

  • 正在使用 DelegatingHandler,重写 SendAsync 以获取正在发送的请求的字节,然后配置 FlurlHttp 设置以使用处理程序选项..?
  • 听起来不错。怎么做?

标签: c# flurl


【解决方案1】:

这是我在评论中描述的代码示例 - 使用 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();
 });

【讨论】:

  • 我们如何将 DelegatingHandler 链接在一起?我已经覆盖了 CreateMessageHandler 以提供代理支持。
  • 我明白了——我必须添加一个链接的构造函数。
  • 是的 - 通过构造函数传入其他处理程序并设置 InnerHandler
  • OK -- 新问题。如果我从 CustomMessageHandler 中的 SendAsync 覆盖中获取 content.LongLength,我如何将其传递给最初调用 SendAsync 的方法?有没有办法从调用者那里获得访问权限?
  • 你可能会在响应消息中的某个地方戳它: var httpResponseMessage = await base.SendAsync(request, cancelToken);然后从 SendAsync 中返回 httpResponseMessage
猜你喜欢
  • 2021-12-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-04-01
相关资源
最近更新 更多