Reputation: 504
How do I have to chain my HttpMessageHandler
s for the HttpClient
to reach my following goal.
I am using the SocketsHttpHandler
as my inner HttpMessageHandler
for HttpClient
with cookie support. On top of the handler I wrote my own LoggingHttpHandler
to log every request including the cookies.
The cookies are not present in the HttpRequestMessage
and the HttpResponseMessage
. They are handled by the internal CookieContainer
of the SocketsHttpHandler
, so I access these cookies inside my LoggingSocketsHttpHandler
.
My solution is like so:
public class LoggingSocketsHttpHandler : DelegatingHandler
{
private readonly SocketsHttpHandler _httpHandler;
public LoggingSocketsHttpHandler(SocketsHttpHandler httpHandler)
: base(httpHandler)
{
_httpHandler = httpHandler;
}
protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request,
CancellationToken cancellationToken)
{
LogRequestStart(request); // Access SocketsHttpHandler.CookieContainer
var response = await base.SendAsync(request, cancellationToken).ConfigureAwait(false);
LogRequestEnd(response); // Access SocketsHttpHandler.CookieContainer
}
}
Works pretty fine. I am writing another HttpMessageHandler
which intercepts the response if a special HTTP status code is detected.
When this occurs the HttpMessageInterceptionHandler
needs to access the CookieContainer
as well and makes another request. This request can be logged if the InnerHandler
is a LoggingSocketsHttpHandler
but should also work with the plain SocketsHttpHandler
.
It seems wrong to me to search inside of those DelegatingHandler
s for as long as a SocketsHttpHandler
is found to get the CookieContainer
. I maybe want to write my own one in the future for example. SocketsHttpHandler
is sealed
also.
The full pipeline would look like:
HttpMessageInterceptionHandler
(1)
-> LoggingSocketsHttpHandler
(2)
-> SocketsHttpHandler
where (1) and (2) needs to access the CookieContainer
.
Anyone knows how to achieve this?
Upvotes: 2
Views: 2176