Skip to content

Instantly share code, notes, and snippets.

@motowilliams
Created February 22, 2012 04:03
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save motowilliams/1881241 to your computer and use it in GitHub Desktop.
Save motowilliams/1881241 to your computer and use it in GitHub Desktop.
aspnet web api json MediaTypeFormatter using Servicestack.Text
public class ServiceStackTextFormatter : MediaTypeFormatter
{
public ServiceStackTextFormatter()
{
// Fill out the mediatype and encoding we support
SupportedMediaTypes.Add(new MediaTypeHeaderValue("application/json"));
Encoding = new UTF8Encoding(false, true);
}
protected override Task<object> OnReadFromStreamAsync(Type type, Stream stream, HttpContentHeaders contentHeaders, FormatterContext formatterContext)
{
// Create task reading the content
return Task.Factory.StartNew(() =>
{
return JsonSerializer.DeserializeFromStream(type, stream);
});
}
protected override Task OnWriteToStreamAsync(Type type, object value, Stream stream, HttpContentHeaders contentHeaders, FormatterContext formatterContext, TransportContext transportContext)
{
// Create task writing the serialized content
return Task.Factory.StartNew(() =>
{
JsonSerializer.SerializeToStream(value, stream);
});
}
protected override bool CanReadType(Type type)
{
if (type == typeof(IKeyValueModel))
return false;
return true;
}
protected override bool CanWriteType(Type type)
{
return true;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment