Skip to content

Instantly share code, notes, and snippets.

@panesofglass
Last active April 24, 2023 17:53
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save panesofglass/a1cfc3c9a3f0d41233ad to your computer and use it in GitHub Desktop.
Save panesofglass/a1cfc3c9a3f0d41233ad to your computer and use it in GitHub Desktop.
How to use base.SendAsync in F# DelegatingHandler
type internal AsyncCallableHandler(messageHandler) =
inherit DelegatingHandler(messageHandler)
member internal x.CallSendAsync(request, cancellationToken) =
base.SendAsync(request, cancellationToken)
let loggingHandler =
{ new DelegatingHandler() with
member x.SendAsync(request, cancellationToken) =
let wrapped = new AsyncCallableHandler(base.InnerHandler)
let workflow = async {
let! requestContent =
request.Content.ReadAsStringAsync()
|> Async.AwaitTask
log requestContent
let! response =
wrapped.CallSendAsync(request, cancellationToken)
|> Async.AwaitTask
let! responseContent =
response.Content.ReadAsStringAsync()
|> Async.AwaitTask
log responseContent
return response
}
Async.StartAsTask(workflow, cancellationToken = cancellationToken)
}
@xperiandri
Copy link

Thanks a lot!

@jkone27
Copy link

jkone27 commented Apr 24, 2023

awesome! this doesnt work instead (or it's buggy as it works only if request is not changed)

let loggingHandler =
    { new DelegatingHandler() with
        member x.SendAsync(request, cancellationToken) =
            let sendBase = base.SendAsync(request, cancellationToken)
            let workflow = task {
                  // your code here, if you change Request it will not change! beware !!!!!
                    return! sendBase
             

@jkone27
Copy link

jkone27 commented Apr 24, 2023

This should maybe be added to the official docs of delegating handlers for F#, without it, e.g. using base.SendAsync even inside a task, the task will not modify the request object, for example, I had a bug related to this in some AspNet code! awesome. Thank you so much @panesofglass 👍

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment