Search code examples
c#.net-core.net-6.0

Output all headers from HttpClient HttpResponseMessage to console


I would like to write all Request and Response Headers to the console.

Inside a console application (created via dotnet new console --framework net5.0) i have basically this code

using System;
using System.Collections.Specialized;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Threading.Tasks;

....

var client = new HttpClient();
var request = new HttpRequestMessage();
request.Method = HttpMethod.Get;
// add uri and header and so on ... 

HttpResponseMessage response = await client.SendAsync(request);
PrintHeaders(response);

My first PrintHeaders() looks like this

public static void PrintHeaders(HttpResponseMessage response)
{
    // cast from HttpRequestHeaders
    // and  from HttpResponseHeaders
    PrintHeaders((HttpHeaders)response.RequestMessage.Headers);  
    PrintHeaders((HttpHeaders)response.Headers); 
}

And the other PrintHeaders() like this

public static void PrintHeaders(HttpHeaders headers)
{
    Console.WriteLine( "   Printing Headers " );
    Console.WriteLine( "   KEY        VALUE" );
    var headersEnumerator = headers.GetEnumerator();        
    while (headersEnumerator.MoveNext())
    {
        Console.WriteLine( " {0,-25} {1}"
            , headersEnumerator.Current.Key
            , String.Join(" ",headersEnumerator.Current.Value.GetEnumerator()) );
    }
    Console.WriteLine();
}

What is working

The code works in so far that it receives a response from the server. And writes headers to the console.

Output

 Printing Headers 
 KEY                       VALUE
 Authorization             System.String[]

 Printing Headers
 KEY                       VALUE
 Date                      System.String[]
 Date                      System.SZGenericArrayEnumerator`1[System.String]
 Connection                System.String[]

As you can see above System.String[] or System.SZGenericArrayEnumerator 1[System.String] is written instead of the acutal value.

// System.String[] for
headersEnumerator.Current.Value.ToString() 

// System.SZGenericArrayEnumerator`1[System.String] for
String.Join(" ",headersEnumerator.Current.Value.GetEnumerator())

What is missing / not working?

Not working is to get the header.value as plain string for example for the header-field date something like Wed, 07 Sep 2022 10:45:04 GMT

Instead i only get System.String[] or something similar.

Question

What can i do to output all header-keys and its values as plain text to the console?


Solution

  • Quick fix is to change:

     Console.WriteLine( " {0,-25} {1}"
                , headersEnumerator.Current.Key
                , String.Join(" ",headersEnumerator.Current.Value.GetEnumerator()) );
    

    To

     Console.WriteLine( " {0,-25} {1}"
                , headersEnumerator.Current.Key
                , String.Join(" ",headersEnumerator.Current.Value) ); //removing GetEnumerator()