Created
February 22, 2012 04:03
-
-
Save motowilliams/1881241 to your computer and use it in GitHub Desktop.
aspnet web api json MediaTypeFormatter using Servicestack.Text
This file contains hidden or 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
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