Created
June 14, 2017 18:33
-
-
Save patbonecrusher/8584f8b8b6be48898e4c11b939215cad to your computer and use it in GitHub Desktop.
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
public class TextMediaTypeFormatter : MediaTypeFormatter | |
{ | |
public TextMediaTypeFormatter() | |
{ | |
SupportedMediaTypes.Add(new MediaTypeHeaderValue("text/plain")); | |
} | |
public override Task<object> ReadFromStreamAsync(Type type, Stream readStream, HttpContent content, IFormatterLogger formatterLogger) | |
{ | |
var taskCompletionSource = new TaskCompletionSource<object>(); | |
try | |
{ | |
var memoryStream = new MemoryStream(); | |
readStream.CopyTo(memoryStream); | |
var s = System.Text.Encoding.UTF8.GetString(memoryStream.ToArray()); | |
taskCompletionSource.SetResult(s); | |
} | |
catch (Exception e) | |
{ | |
taskCompletionSource.SetException(e); | |
} | |
return taskCompletionSource.Task; | |
} | |
public override Task WriteToStreamAsync(Type type, object value, Stream writeStream, HttpContent content, System.Net.TransportContext transportContext, System.Threading.CancellationToken cancellationToken) | |
{ | |
var buff = System.Text.Encoding.UTF8.GetBytes(value.ToString()); | |
return writeStream.WriteAsync(buff, 0, buff.Length, cancellationToken); | |
} | |
public override bool CanReadType(Type type) | |
{ | |
return type == typeof(string); | |
} | |
public override bool CanWriteType(Type type) | |
{ | |
return type == typeof(string); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment