Printing Raw HTTP Requests / Responses in C#
When debugging web services in .NET, I have an occasional need to print raw HTTP requests and responses. Tools like Fiddler are very helpful for this purpose, but a bug can still occur in cloud environments where Fiddler cannot capture traffic.
I am surprised C# does not have built-in methods to print raw HTTP request and response strings. The HttpResponseMessage class, for example, has a ToString() method that will return most response properties and headers. But the returned string is not in an HTTP message format, and the response body is omitted entirely.
I haven’t found an elegant solution for this problem on answer sites like StackOverflow, so I decided to implement my own. The Gist below contains extension methods to print raw HTTP requests and responses. One file is server-side using ASP.NET Core. The other is client-side using HttpClient.
Here is an example output showing a request and response to my website:
1 | Request: |
I can’t guarantee every request and response will be printed exactly to the HTTP specification. Moreover, for obvious security reasons, you should not log request and response bodies in production environments. But this code should work nicely for troubleshooting development environments.