Guest User

Untitled

a guest
Jul 16th, 2018
75
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.57 KB | None | 0 0
  1. namespace Owin
  2. {
  3. using System;
  4. using System.Collections.Generic;
  5. using System.Text;
  6. using System.IO;
  7.  
  8. public interface IResponseHandler
  9. {
  10. Type TypeToHandle { get; }
  11. void WriteToStream(object value, Stream stream);
  12. }
  13.  
  14. public interface IResponseHandler<T> : IResponseHandler
  15. {
  16. void WriteToStream(T value, Stream stream);
  17. }
  18.  
  19. public static class OWIN
  20. {
  21. static IDictionary<Type, Action<object, Stream>> responseHandlers = new Dictionary<Type, Action<object, Stream>>();
  22.  
  23. public static void AddDefaultHandlers()
  24. {
  25. AddRequestHandler<byte[]>((x, s) => s.Write(x, 0, x.Length));
  26.  
  27. AddRequestHandler<string>((x, s) =>
  28. {
  29. byte[] buffer = Encoding.UTF8.GetBytes(x);
  30. s.Write(buffer, 0, buffer.Length);
  31. });
  32.  
  33. AddRequestHandler<ArraySegment<byte>>((x, s) => s.Write(x.Array, 0, xas.Array.Length));
  34. }
  35.  
  36. public static void AddResponseHandler<T>(Action<T, Stream> handler)
  37. {
  38. responseHandlers[typeof(T)] = handler;
  39. }
  40.  
  41. public static void AddResponseHandler<T>(IResponseHandler<T> handler)
  42. {
  43. responseHandlers[handler.TypeToHandle] = (x, s) => handler.WriteToStream(x, s);
  44. }
  45.  
  46. public static void AddResponseHandler(IResponseHandler handler)
  47. {
  48. responseHandlers[handler.TypeToHandle] = (x, s) => handler.WriteToStream(x, s);
  49. }
  50.  
  51. public static Action<T, Stream> GetResponseHandler<T>()
  52. {
  53. Type objectType = typeof(T);
  54. Action<T, Stream> handler = null;
  55. if (!responseHandlers.TryGetValue(objectType, out handler))
  56. {
  57. if (objectType.IsGenericType)
  58. objectType = objectType.GetGenericTypeDefinition();
  59. responseHandlers.TryGetValue(objectType, out handler);
  60. }
  61.  
  62. Action<T, Stream> action = handler as Action<T, Stream>;
  63. return action != null ? action : (x, s) => { };
  64. }
  65.  
  66.  
  67. public static void WriteBodyToStream(this IResponse response, Stream stream)
  68. {
  69. var body = response.GetBody();
  70. using (var enumerator = body.GetEnumerator())
  71. {
  72. while (enumerator.MoveNext())
  73. {
  74. var value = enumerator.Current;
  75. if (value != null)
  76. {
  77. OWIN.GetResponseHandler(value.GetType())(value, stream);
  78. }
  79. }
  80. }
  81. }
  82. }
  83. }
Add Comment
Please, Sign In to add comment