Last active
March 29, 2024 14:27
-
-
Save tonysneed/d7f6533e12e5f7e1c0fc to your computer and use it in GitHub Desktop.
Serialization Helper for ASP.NET Web API
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.Net.Http.Formatting; | |
using System.Runtime.Serialization; | |
using Newtonsoft.Json; | |
using WebApiContrib.Formatting; | |
namespace WebApiContrib | |
{ | |
public static class SerializationHelper | |
{ | |
/// <summary> | |
/// Configure serializer for Json formatter to handle cyclical references. | |
/// </summary> | |
/// <param name="jsonFormatter">Json media type formatter</param> | |
public static void ConfigJsonSerializer(this BaseJsonMediaTypeFormatter jsonFormatter) | |
{ | |
jsonFormatter.SerializerSettings.PreserveReferencesHandling = | |
PreserveReferencesHandling.All; | |
} | |
/// <summary> | |
/// Configure serializer for Xml formatter to handle cyclical references. | |
/// </summary> | |
/// <param name="xmlFormatter">Web API Xml Formatter.</param> | |
/// <param name="types">Types returned from controller actions.</param> | |
public static void ConfigXmlSerializer | |
(this XmlMediaTypeFormatter xmlFormatter, params Type[] types) | |
{ | |
foreach (var type in types) | |
{ | |
var serializer = new DataContractSerializer(type, | |
null, int.MaxValue, false, true, null); | |
xmlFormatter.SetSerializer(type, serializer); | |
} | |
} | |
/// <summary> | |
/// Configure ProtoBuf formatter to handle cyclical references. | |
/// </summary> | |
/// <param name="types"></param> | |
public static void ConfigProtoBufFormatter(params Type[] types) | |
{ | |
foreach (var type in types) | |
{ | |
var meta = ProtoBufFormatter.Model.Add(type, false); | |
var props = type.GetProperties(); | |
for (var i = 0; i < props.Length; i++) | |
{ | |
meta.Add(i + 1, props[i].Name); | |
} | |
meta.AsReferenceDefault = true; | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Here is a sample WebApiConfig class that uses the serialization helper: