- Published on
cURL Delegating Handler
- Authors
- Name
- Srinjoy Santra
- @s_srinjoy
CurlDelegatingHandler
This package generates curl by extending HttpClient of .NET with DelegatingHandler i.e. Custom Message Handler.
A DelegatingHandler
in .NET's HttpClient
pipeline is a customizable middleware component that processes HTTP requests and responses. It allows developers to add pre-processing and post-processing logic, such as logging, authentication, retry policies, or caching. By overriding the SendAsync
method, developers can create handlers that manipulate requests before passing them down the chain to other handlers or return responses directly. Multiple DelegatingHandler
instances can be chained to create a sequence of processing steps, enhancing code reusability and composability. This approach enables flexible and maintainable handling of HTTP operations in .NET applications.
How it works
Any requests made with HttpClient
is sent through the client pipeline containing only one message handler named CurlDelegatingHandler
The curl is returned in the response header named outputCurl
.
To prevent sending request to the network (with default HttpClientHandler
), the header CanSend: False
should be added to the request.
Currently supported HTTP verbs are as follows
GET
POST
PUT
DELETE
Sample console application
using System.Text;
using CurlGenerator;
string url = "https://jsonplaceholder.typicode.com/posts";
string jsonPayload = @"{""title"": ""New Post"", ""body"": ""This is the body of the new post"", ""userId"": 1}";
var content = new StringContent(jsonPayload, Encoding.UTF8, "application/json");
var httpClient = new HttpClient(new CurlDelegatingHandler());
httpClient.DefaultRequestHeaders.Add(Settings.CanSend, "False");
var result = await httpClient.PostAsync(url, content);
string outputCurl = result.Headers.GetValues(Settings.OutputCurl).FirstOrDefault();
Console.WriteLine(outputCurl);
Output
curl -X POST 'https://jsonplaceholder.typicode.com/posts' -H 'Content-Type: application/json; charset=utf-8' -H 'Content-Length: 78' -d '{"title": "New Post", "body": "This is the body of the new post", "userId": 1}'
How it was tested
The test cases were inspired from Postman Code Generators.
Why is it needed
There are many online sources that tell how to convert curl to its equivalent HTTPClient code in C#. Yet, when I try to find the other way around, there's hardly any. It can be used to help debugging, log and trace incoming request.
Here is what a kind Reddit user had to tell about it.
I like it for being able to make your requests troubleshootable by another means. It can also expose what a request looks like. OP, nice work. Does a thing, does it without complication, looks like it does it well
Way Forward
- Further decouple builder methods.
- Support more
Settings
like Postman.
Deployment
The package has been released on nuget.org