0

I would like to know how many bytes were actually transmitted when using Post or PostAsync. I'm using code similar to the following. I could look at the bytes of the filePath, but in my real code, I'm doing some manipulation to the file stream between being read and sent. If you pull out the MyFilteredContent line, how would you do it?

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");
    }
}
101010
  • 14,866
  • 30
  • 95
  • 172
  • Is using a DelegatingHandler, overriding SendAsync to get the bytes of the request being sent and then configuring FlurlHttp settings to use the handler an option..? – TheRock Jun 13 '18 at 18:09
  • That sounds good. How to do it? – 101010 Jun 13 '18 at 18:09

1 Answers1

0

Here's a code sample of what I described in the comment - using DelegatingHandler, overriding SendAsync to get the bytes of the request being sent and then configuring FlurlHttp settings to use the handler:

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();
 });
TheRock
  • 1,513
  • 1
  • 18
  • 19
  • How do we chain the DelegatingHandlers together? I'm already overriding CreateMessageHandler to provide proxy support. – 101010 Jun 13 '18 at 18:19
  • I got it -- I have to add a constructor that chains. – 101010 Jun 13 '18 at 18:21
  • Yep - pass in other handler through the constructor and set the InnerHandler – TheRock Jun 13 '18 at 18:24
  • OK -- new problem. If I get the content.LongLength from inside the SendAsync override in the CustomMessageHandler, how do I get that to the method that originally called SendAsync? Is there a way to get access to it from the caller? – 101010 Jun 13 '18 at 18:37
  • You could possibly poke it in somewhere in the response message: var httpResponseMessage = await base.SendAsync(request, cancellationToken); then return the httpResponseMessage from SendAsync – TheRock Jun 13 '18 at 18:44