Last active
September 3, 2015 22:02
-
-
Save arcware/1e516bc6d5c9be6d4581 to your computer and use it in GitHub Desktop.
Serialize HttpHeaders as JSON
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.Collections.Generic; | |
using System.Linq; | |
using System.Net.Http.Headers; | |
using Newtonsoft.Json; | |
public static class HttpHeadersExtensions | |
{ | |
public static string ToJson(this HttpHeaders headers) | |
{ | |
var dict = ToDictionary(headers); | |
return JsonConvert.SerializeObject(dict, Formatting.None); | |
} | |
public static string ToJsonIndented(this HttpHeaders headers) | |
{ | |
var dict = ToDictionary(headers); | |
return JsonConvert.SerializeObject(dict, Formatting.Indented); | |
} | |
private static Dictionary<string, string> ToDictionary(this HttpHeaders headers) | |
{ | |
var dict = new Dictionary<string, string>(); | |
foreach (var item in headers.ToList()) | |
{ | |
if (item.Value != null) | |
{ | |
var header = String.Empty; | |
foreach (var value in item.Value) | |
{ | |
header += value + " "; | |
} | |
// Trim the trailing space and add item to the dictionary | |
header = header.TrimEnd(" ".ToCharArray()); | |
dict.Add(item.Key, header); | |
} | |
} | |
return dict; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment