Skip to content

Instantly share code, notes, and snippets.

@danielwertheim
Created September 8, 2012 17:38
Show Gist options
  • Select an option

  • Save danielwertheim/3677744 to your computer and use it in GitHub Desktop.

Select an option

Save danielwertheim/3677744 to your computer and use it in GitHub Desktop.
WebAPI ServiceStack
using System;
using System.IO;
using System.Net;
using System.Net.Http;
using System.Net.Http.Formatting;
using System.Net.Http.Headers;
using System.Text;
using System.Threading.Tasks;
using EnsureThat;
using iLogMyDay.Core.Serialization;
namespace iLogMyDay.WebApp.Core
{
public class ServiceStackFormatter : MediaTypeFormatter
{
protected readonly ISerializer Serializer;
public ServiceStackFormatter(ISerializer serializer)
{
Ensure.That(serializer, "serializer").IsNotNull();
Serializer = serializer;
SupportedMediaTypes.Add(new MediaTypeWithQualityHeaderValue("application/json"));
SupportedMediaTypes.Add(new MediaTypeWithQualityHeaderValue("text/json"));
SupportedEncodings.Add(new UTF8Encoding(encoderShouldEmitUTF8Identifier: false, throwOnInvalidBytes: true));
SupportedEncodings.Add(new UnicodeEncoding(bigEndian: false, byteOrderMark: true, throwOnInvalidBytes: true));
}
public override bool CanReadType(Type type)
{
return true;
}
public override bool CanWriteType(Type type)
{
return true;
}
public override Task<object> ReadFromStreamAsync(Type type, Stream readStream, HttpContent content, IFormatterLogger formatterLogger)
{
return Task<object>.Factory.StartNew(() => Serializer.Deserialize(type, readStream));
}
public override Task WriteToStreamAsync(Type type, object value, Stream writeStream, HttpContent content, TransportContext transportContext)
{
return Task.Factory.StartNew(() => Serializer.Serialize(type, value, writeStream));
}
}
}
private static void SetCustomJsonFormatter(HttpConfiguration apiConfig)
{
var jsonFormatter = new ServiceStackFormatter(WebAppRuntime.Instance.ObjectResolver.Resolve<ISerializer>());
var foundFormatterIndex = false;
for (var i = 0; i < apiConfig.Formatters.Count; i++)
{
var f = apiConfig.Formatters[i];
if (f.SupportedMediaTypes.Any(m => m.MediaType.Contains("json")))
{
foundFormatterIndex = true;
apiConfig.Formatters[i] = jsonFormatter;
break;
}
}
if (!foundFormatterIndex)
apiConfig.Formatters.Insert(0, jsonFormatter);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment