boa-constrictor
boa-constrictor copied to clipboard
[FEATURE]: Improvements to RestSharp dumping
Description
Since we've updated to the latest RestSharp there may be new ways to approach dumping from.
I came across this comment and got inspired.
You could in theory, write a message handler that dumps the raw HttpRequestMessage
rather than the RestSharp object. The nice part about this is HttpRequestMessage
already has a ToString()
overload. So there isn't much code needed to get a nicely formatted dump.
At first glance, it's pretty easy to get working.
- Write a
DelagatingHandler
that takes in BoasILogger
public class LoggingDelegatingHandler : DelegatingHandler
{
public ILogger logger;
public LoggingDelegatingHandler(ILogger logger, HttpMessageHandler innerHandler) : base(innerHandler)
{
this.logger = logger;
}
protected override HttpResponseMessage Send(HttpRequestMessage request, CancellationToken cancellationToken)
{
logger.Log(request.ToString());
return base.Send(request, cancellationToken);
}
protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
{
logger.Log(request.ToString());
return base.SendAsync(request, cancellationToken);
}
}
- Configure your
RestClient
to use the custom message handler
private RestClient client;
[SetUp]
public void Initialize()
{
var options = new RestClientOptions
{
BaseUrl = new Uri( "https://dog.ceo/"),
ConfigureMessageHandler = handler => new LoggingDelegatingHandler(new ConsoleLogger(), handler)
};
this.client = new RestClient(options);
}
- Make your request
[Test]
public void DumpTest()
{
var request = new RestRequest("api/breeds/image/random");
this.client.Get(request);
}
Since I configured this to use Boas ConsoleLogger
the following shows up in the TestOutput window. But of course you could write a logger/Delegating Handler to log to file if you prefer 👍
2023-05-25 22:04:22Z [INFO] Method: GET, RequestUri: 'https://dog.ceo/api/breeds/image/random', Version: 1.1, Content: <null>, Headers:
{
Accept: application/json, text/json, text/x-json, text/javascript, application/xml, text/xml
User-Agent: RestSharp/110.2.0.0
}
All this to say, I believe we could replace most of the current RequestDumping feature with a custom message handler.
Alternatives
Work with what we got. Refactor the serialization objects to comply with the modern RestSharp objects.
Anything else?
I don't use the dumping feature myself that often so I could be missing something. Could require a different implementation depending on what version of .NET you're on... Still prefer this over versions of RestSharp.
Commitments
- [x] I agree to follow Boa Constrictor's Code of Conduct.
- [ ] I want to work on this issue myself. (This is voluntary, not required.)