Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
Using ServiceStack.Test JsonSerializer in a Web API MediaTypeFormatter
using System.Net.Http.Formatting;
using System.Net.Http.Headers;
using System.Text;
using System.Threading.Tasks;
using ServiceStack.Text;
namespace HttpClientTest.Formatters {
public class ServiceStackFormatter : MediaTypeFormatter {
public ServiceStackFormatter() {
// Fill out the mediatype and encoding we support
SupportedMediaTypes.Add(new MediaTypeHeaderValue("application/json"));
Encoding = new UTF8Encoding(false, true);
protected override bool CanReadType(System.Type type) {
return type != typeof(IKeyValueModel);
protected override bool CanWriteType(System.Type type) {
return true;
protected override Task<object> OnReadFromStreamAsync(System.Type type, System.IO.Stream stream, HttpContentHeaders contentHeaders, FormatterContext formatterContext) {
return Task.Factory.StartNew(() => JsonSerializer.DeserializeFromStream(type, stream));
protected override Task OnWriteToStreamAsync(System.Type type, object value, System.IO.Stream stream, HttpContentHeaders contentHeaders, FormatterContext formatterContext, System.Net.TransportContext transportContext) {
return Task.Factory.StartNew(() => JsonSerializer.SerializeToStream(value, type, stream));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment