Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
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