c# - 使用 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");
}
}
解决方案
这是我在评论中描述的代码示例 - 使用 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();
});
推荐阅读
- c# - UniRx 如何通过将自身与另一个流组合来在流中发布新值
- python - 随机模块的随机random.pyi文件中没有任何函数定义的多个def?
- oracle - 在 Oracle 物化视图中用某个字符串替换空列
- powershell - 使用 PowerShell 将 CD 放入某个位置的最新子文件夹
- c# - AvolonDock 查找所有布局
- java - 调用调用 Graph API 的 Web api 的 Web 应用程序 -
- amazon-web-services - 使用 java 访问 AWS ECS 负载均衡器端点
- netlogo - 在 netlogo 中,乌龟走到墙而不是门
- javascript - 使用 js 文件中的变量到另一个 js 文件中
- nginx - 由于 Ubuntu 16.04 上的模块差异,Nginx 从 1.16 升级到 1.18 失败