Skip to content

Instantly share code, notes, and snippets.

@arcware
Last active September 3, 2015 22:02
Show Gist options
  • Save arcware/1e516bc6d5c9be6d4581 to your computer and use it in GitHub Desktop.
Save arcware/1e516bc6d5c9be6d4581 to your computer and use it in GitHub Desktop.
Serialize HttpHeaders as JSON
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