Debugging HTTP Requests in .Net Core | by Edson Moisinho | Aug, 2022

Intercept requests and generate a curl command automatically

Photo by Gundula Vogel from Pixabay

When receiving errors resulting from HTTP requests of a Web APIs is very common start investigating the issue extracting the exact request that the app is doing and preparing a curl command or a postman call to reproduce the issue.

This is not a complex task, but it consumes a lot of time since we need to run our apps identify the request, inspect the address, parameters, headers, keys and etc, copy it to a file, and build the curl command.

Some people even spend some time, installing sniffer apps like Fiddler, and Wireshark to inspect all the HTTP traffic from the computer, or even serializing the requests and log it into text files, those approaches certainly helps to solve the problems but it requires installing additional apps or writing custom log routines many times.

In this article, I will show how to use HTTP Message Handlers to intercept HTTP requests and automatically generate curl commands for your requests in a very easy and quick way.

If you are thinking about the native HTTP log handlers in Asp.Net 6.0, you are absolutely right, we do not need custom code.

If you are using Asp.Net 6.0, check the documentation here and log all your requests even easier than the techniques presented and this article

But, If you are using older versions such as 5.0 or 3.1 (or older) maybe this article can be helpful for you.

Another reason to keep reading is to understand how we can take advantage of the custom message handlers, not only for log purposes but also for any other needs (as mentioned later in this article)

An HTTP Message Handler is a class that receives an HTTP request and returns an HTTP response (simple like that).

The Asp.Net Web API has a few built-in message handlers that create a nested (and native) calls pipeline.

We can create a custom handler inheriting from the DelegatingHandler class and add it to the pipeline.

Before starting creating our example Web API, I was searching for free APIs to use in my tests and I found two quite interesting:

  • Nationalize IO — This API uses a GET method and it predicts the nationality of a person given their name.
  • Yoda Translator API — The Yoda translator API uses a POST method and will translate an English phrase to the Yoda language, which basically backward the original sentences.

So based on these two APIs, my proposal is to create a new Web API that from a name, predicts the nationality of a person and request to the Yoda translator the phrase Master {NAME} has lost {COUNTRY} and expecting a result like Lost {COUNTRY}, master {NAME} has

Nice and simple isn’t, so let’s build it.

Create a new folder on our computer, type mkdir http-to-curl in a command line and press Enter.

Then enter in the folder running cd http-to-curl and create a new Web API running dotnet new webapi

Now, let’s install the Refit dependencies to be able to easily make requests with it, run dotnet add package Refit --version 6.3.2 and dotnet add package Refit.HttpClientFactory --version 6.3.2

Open the Visual Studio Code running code . and the structure must be very similar to that one:

Initial app structure

Next, create a new API folder and add the INationalizeApi.csclass

INationalizeApi class

Also, add the IYodaTranslationApi.csclass

IYodaTranslationApi class

Then, add the refit clients in the Program.cs file (lines 10 and 14):

Program class

Remove the WeatherForecastController and the WeatherForecast class and add the CompositeApiController as below

CompositeApiController class

Our API is ready to run, type dotnet run in the console and make a request typing curl --location --insecure --request GET 'https://localhost:7127/Pietro' --header 'keya:valuea' --header 'keyb:valueb' (note that the headers are only to example purposes, the insecure option is to avoid the certificate and maybe you will need to adapt the port to the same as your app is running)

If everything is ok, you will see the following result message on the command line: Lost italia, Pietro has

Mission accomplished, we have an example app.

Now, prepare for the best part, let’s create our custom handler, create the logic to inspect the request and build the curl.

HttpToCurlHandlers class

This class is very simple, first, we override the SendAsyncmethod, which will be executed before a request happens, and for the interception here will basically need to add methods to log the request and the response.

To make easier to search in the logs, I am generating a GUID to will facilitate matching requests to a responses in the logs.

The log methods are very simple also, they start logging some hardcode curl syntax, then it logs the address, method, headers, and body of the request object.

The main point here is that should be totally customizable, and you can do whatever you want.

The last step is to associate the handlers with our Refit client, in order to do that we need to add to Program.cs a call to .addHttpMessageHandler<HttpToCurlHandler> method to each Refit call that you can use the handler (lines 4 and 9) and register the handler in the services (line 11)

Adapting our existing code to use the handler must look exactly like this:

Program class after adding the handlers

Since I am using System.Diagnostics.Debug.WriteLine() method to log, we will only be able to see the logs when running the app in debug mode, if you need something different than that, you only need to change the way the handler is logging the info.

Press F5 to start the app in debug mode, and request again as we did in the previous step.

Looking in the Debug Console window and filtering for REFIT LOG you will be able to see all the curls generated by the handler.

Debug Console windows on Visual Studio Code

Yeah, that’s working.

As I have explained at the beginning of this article, the HTTP Message Handler can be used for any other needs, such as authorization, headers customization, complementing information, cryptography, and so on, feel free to use it wisely

If you want to run the example project that I used to create this article, feel free to clone it from my GitHub repo.

I hope this article can be useful for you as it was for me, thank you for reading until here, and see you next time

News Credit

%d bloggers like this: