Created
December 8, 2010 20:37
-
-
Save jasonmead/733877 to your computer and use it in GitHub Desktop.
OWIN GetBody Handler
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
namespace Owin | |
{ | |
using System; | |
using System.Collections.Generic; | |
using System.Text; | |
using System.IO; | |
public interface IResponseHandler | |
{ | |
Type TypeToHandle { get; } | |
void WriteToStream(object value, Stream stream); | |
} | |
public static class OWIN | |
{ | |
static IDictionary<Type, object> responseHandlers = new Dictionary<Type, object>(); | |
public static void AddDefaultHandlers() | |
{ | |
AddRequestHandler<byte[]>((x, s) => | |
{ | |
var xb = x as byte[]; | |
s.Write(xb, 0, xb.Length); | |
}); | |
AddRequestHandler<string>((x, s) => | |
{ | |
var xs = x as string; | |
byte[] buffer = Encoding.UTF8.GetBytes(xs); | |
s.Write(buffer, 0, buffer.Length); | |
}); | |
AddRequestHandler<ArraySegment<byte>>((x, s) => | |
{ | |
var xas = (ArraySegment<byte>)x; | |
s.Write(xas.Array, 0, xas.Array.Length); | |
}); | |
} | |
public static void AddRequestHandler<T>(Action<object, Stream> handler) | |
{ | |
responseHandlers[typeof(T)] = handler; | |
} | |
public static void AddRequestHandler(IResponseHandler handler) | |
{ | |
responseHandlers[handler.TypeToHandle] = handler; | |
} | |
public static Action<object, Stream> GetResponseHandler(Type objectType) | |
{ | |
object handler = null; | |
if (!responseHandlers.TryGetValue(objectType, out handler)) | |
{ | |
if (objectType.IsGenericType) | |
objectType = objectType.GetGenericTypeDefinition(); | |
responseHandlers.TryGetValue(objectType, out handler); | |
} | |
Action<object, Stream> action = handler as Action<object, Stream>; | |
if (action != null) return action; | |
IResponseHandler responseHandler = handler as IResponseHandler; | |
if (responseHandler != null) return responseHandler.WriteToStream; | |
return (x, s) => { }; | |
} | |
public static void WriteBodyToStream(this IResponse response, Stream stream) | |
{ | |
var body = response.GetBody(); | |
using (var enumerator = body.GetEnumerator()) | |
{ | |
while (enumerator.MoveNext()) | |
{ | |
var value = enumerator.Current; | |
if (value != null) | |
{ | |
OWIN.GetResponseHandler(value.GetType())(value, stream); | |
} | |
} | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
One, because this is just a snippet of code off the top of my head and I haven't actually tested it yet.
Two, because GetBody returns IEnumerable, I can only pass an object typed as 'object' to the action. If the action expects T and gets an object, the Action will treat it as object anyway.