The next generation of the Teknik Services. Written in ASP.NET. https://www.teknik.io/
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

ActionResultHelper.cs 2.8KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  1. using System;
  2. using System.Collections.Generic;
  3. using System.IO;
  4. using System.IO.Compression;
  5. using System.Linq;
  6. using System.Net;
  7. using System.Web;
  8. using System.Web.Mvc;
  9. namespace Teknik.Helpers
  10. {
  11. /// <summary>
  12. /// Result for relaying an HttpWebResponse
  13. /// </summary>
  14. public class HttpWebResponseResult : ActionResult
  15. {
  16. private readonly HttpWebResponse _response;
  17. private readonly ActionResult _innerResult;
  18. /// <summary>
  19. /// Relays an HttpWebResponse as verbatim as possible.
  20. /// </summary>
  21. /// <param name="responseToRelay">The HTTP response to relay</param>
  22. public HttpWebResponseResult(HttpWebResponse responseToRelay)
  23. {
  24. if (responseToRelay == null)
  25. {
  26. throw new ArgumentNullException("response");
  27. }
  28. _response = responseToRelay;
  29. Stream contentStream;
  30. if (responseToRelay.ContentEncoding.Contains("gzip"))
  31. {
  32. contentStream = new GZipStream(responseToRelay.GetResponseStream(), CompressionMode.Decompress);
  33. }
  34. else if (responseToRelay.ContentEncoding.Contains("deflate"))
  35. {
  36. contentStream = new DeflateStream(responseToRelay.GetResponseStream(), CompressionMode.Decompress);
  37. }
  38. else
  39. {
  40. contentStream = responseToRelay.GetResponseStream();
  41. }
  42. if (string.IsNullOrEmpty(responseToRelay.CharacterSet))
  43. {
  44. // File result
  45. _innerResult = new FileStreamResult(contentStream, responseToRelay.ContentType);
  46. }
  47. else
  48. {
  49. // Text result
  50. var contentResult = new ContentResult();
  51. contentResult = new ContentResult();
  52. contentResult.Content = new StreamReader(contentStream).ReadToEnd();
  53. _innerResult = contentResult;
  54. }
  55. }
  56. public override void ExecuteResult(ControllerContext context)
  57. {
  58. var clientResponse = context.HttpContext.Response;
  59. clientResponse.StatusCode = (int)_response.StatusCode;
  60. foreach (var headerKey in _response.Headers.AllKeys)
  61. {
  62. switch (headerKey)
  63. {
  64. case "Content-Length":
  65. case "Transfer-Encoding":
  66. case "Content-Encoding":
  67. // Handled by IIS
  68. break;
  69. default:
  70. clientResponse.AddHeader(headerKey, _response.Headers[headerKey]);
  71. break;
  72. }
  73. }
  74. _innerResult.ExecuteResult(context);
  75. }
  76. }
  77. }