RShome
RShome

Reputation: 537

How to output request headers to a string in C#

I would like to add two custom headers for a DELETE request to a string.

I have the following code

        Dictionary<string, string> customHeaders = new Dictionary<string, string>();
        customHeaders.Add("If-Match", passedEtag);
        customHeaders.Add("context_study_site", "edc42643-27b5-428e-b8ae-2fa19bfb457a");

I have tried the following

        StringBuilder sb = new StringBuilder();
        sb.Append(Environment.NewLine);
        sb.Append(Environment.NewLine + "Context headers passed in the request" + Environment.NewLine);
        Dictionary<string, string> customHeaders = new Dictionary<string, string>();
        customHeaders.Add("If-Match", passedEtag);
        customHeaders.Add("context_study_site", "edc42643-27b5-428e-b8ae-2fa19bfb457a");
        string test = customHeaders.ToString();
        File.WriteAllText("C:\\Testing", "headersoutput.txt");

But I get the following

  System.Collections.Generic.Dictionary`2[System.String,System.String]
  System.Collections.Generic.Dictionary`2[System.String,System.String]

Rather than the two header key value pairs.

Any ideas much appreciated. Thanks in advance.

Upvotes: 0

Views: 1390

Answers (1)

Prasad Telkikar
Prasad Telkikar

Reputation: 16049

Instead of .ToString() you need to Serialize your dictionary using JsonConvert.SerializeObjec()

var jsonDict = JsonConvert.SerializeObject( myDictionary );

Then write it to a file,

 File.WriteAllText(@"C:\Testing\headersoutput.txt", jsonDict);

Why you are getting System.Collections.Generic.Dictionary2[System.String,System.String] in the your file?

  • You are trying to convert a Dictionary to string using .ToString() method. You are not overriding its basic functionality, so it calls the basic implementation of .ToString() method present in Object class.

Returns a string that represents the current object.

MSDN: Basic implementation of Object.ToString()


How we solved it?

Serializes the specified object to a JSON string.

Upvotes: 1

Related Questions