ContentTypes.cs 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. using System;
  2. using System.Collections.Generic;
  3. using System.IO;
  4. using System.Text;
  5. using MediaBrowser.Model.Services;
  6. namespace ServiceStack.Host
  7. {
  8. public class ContentTypes
  9. {
  10. public static ContentTypes Instance = new ContentTypes();
  11. public void SerializeToStream(IRequest req, object response, Stream responseStream)
  12. {
  13. var contentType = req.ResponseContentType;
  14. var serializer = GetResponseSerializer(contentType);
  15. if (serializer == null)
  16. throw new NotSupportedException("ContentType not supported: " + contentType);
  17. var httpRes = new HttpResponseStreamWrapper(responseStream, req)
  18. {
  19. Dto = req.Response.Dto
  20. };
  21. serializer(req, response, httpRes);
  22. }
  23. public Action<IRequest, object, IResponse> GetResponseSerializer(string contentType)
  24. {
  25. var serializer = GetStreamSerializer(contentType);
  26. if (serializer == null) return null;
  27. return (httpReq, dto, httpRes) => serializer(httpReq, dto, httpRes.OutputStream);
  28. }
  29. public Action<IRequest, object, Stream> GetStreamSerializer(string contentType)
  30. {
  31. switch (GetRealContentType(contentType))
  32. {
  33. case "application/xml":
  34. case "text/xml":
  35. case "text/xml; charset=utf-8": //"text/xml; charset=utf-8" also matches xml
  36. return (r, o, s) => ServiceStackHost.Instance.SerializeToXml(o, s);
  37. case "application/json":
  38. case "text/json":
  39. return (r, o, s) => ServiceStackHost.Instance.SerializeToJson(o, s);
  40. }
  41. return null;
  42. }
  43. public Func<Type, Stream, object> GetStreamDeserializer(string contentType)
  44. {
  45. switch (GetRealContentType(contentType))
  46. {
  47. case "application/xml":
  48. case "text/xml":
  49. case "text/xml; charset=utf-8": //"text/xml; charset=utf-8" also matches xml
  50. return ServiceStackHost.Instance.DeserializeXml;
  51. case "application/json":
  52. case "text/json":
  53. return ServiceStackHost.Instance.DeserializeJson;
  54. }
  55. return null;
  56. }
  57. private static string GetRealContentType(string contentType)
  58. {
  59. return contentType == null
  60. ? null
  61. : contentType.Split(';')[0].ToLower().Trim();
  62. }
  63. }
  64. }