BaseHandler.cs 2.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Collections.Specialized;
  4. using System.IO;
  5. using System.IO.Compression;
  6. namespace MediaBrowser.Common.Net.Handlers
  7. {
  8. public abstract class BaseHandler
  9. {
  10. /// <summary>
  11. /// Response headers
  12. /// </summary>
  13. public IDictionary<string, string> Headers = new Dictionary<string, string>();
  14. /// <summary>
  15. /// The action to write the response to the output stream
  16. /// </summary>
  17. public Action<Stream> WriteStream { get; set; }
  18. /// <summary>
  19. /// The original RequestContext
  20. /// </summary>
  21. public RequestContext RequestContext { get; set; }
  22. /// <summary>
  23. /// The original QueryString
  24. /// </summary>
  25. protected NameValueCollection QueryString
  26. {
  27. get
  28. {
  29. return RequestContext.Request.QueryString;
  30. }
  31. }
  32. /// <summary>
  33. /// Gets the MIME type to include in the response headers
  34. /// </summary>
  35. public abstract string ContentType { get; }
  36. /// <summary>
  37. /// Gets the status code to include in the response headers
  38. /// </summary>
  39. public virtual int StatusCode
  40. {
  41. get
  42. {
  43. return 200;
  44. }
  45. }
  46. /// <summary>
  47. /// Gets the cache duration to include in the response headers
  48. /// </summary>
  49. public virtual TimeSpan CacheDuration
  50. {
  51. get
  52. {
  53. return TimeSpan.FromTicks(0);
  54. }
  55. }
  56. /// <summary>
  57. /// Gets the last date modified of the content being returned, if this can be determined.
  58. /// This will be used to invalidate the cache, so it's not needed if CacheDuration is 0.
  59. /// </summary>
  60. public virtual DateTime? LastDateModified
  61. {
  62. get
  63. {
  64. return null;
  65. }
  66. }
  67. public virtual bool CompressResponse
  68. {
  69. get
  70. {
  71. return true;
  72. }
  73. }
  74. public BaseHandler()
  75. {
  76. WriteStream = s =>
  77. {
  78. WriteReponse(s);
  79. s.Dispose();
  80. };
  81. }
  82. private void WriteReponse(Stream stream)
  83. {
  84. if (CompressResponse)
  85. {
  86. using (DeflateStream compressedStream = new DeflateStream(stream, CompressionLevel.Fastest, false))
  87. {
  88. WriteResponseToOutputStream(compressedStream);
  89. }
  90. }
  91. else
  92. {
  93. WriteResponseToOutputStream(stream);
  94. }
  95. }
  96. protected abstract void WriteResponseToOutputStream(Stream stream);
  97. }
  98. }