WebGetModule.cs 3.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104
  1. using System;
  2. using System.Collections.Concurrent;
  3. using System.Collections.Generic;
  4. using System.Configuration;
  5. using System.EnterpriseServices;
  6. using System.IO;
  7. using System.Linq;
  8. using System.Net;
  9. using System.Net.Http;
  10. using System.Web;
  11. using System.Web.Services.Configuration;
  12. namespace WebGet
  13. {
  14. public class WebGetModule : IHttpModule
  15. {
  16. private static readonly ConcurrentDictionary<string, DownloadState> Sessions = new ConcurrentDictionary<string, DownloadState>();
  17. public void Init(HttpApplication context)
  18. {
  19. context.PostMapRequestHandler += ContextOnPostMapRequestHandler;
  20. }
  21. private void ContextOnPostMapRequestHandler(object sender, EventArgs e)
  22. {
  23. var ctx = HttpContext.Current;
  24. var req = ctx.Request;
  25. var qs = req.QueryString;
  26. var rsp = ctx.Response;
  27. if (qs["pass"] != ConfigurationManager.AppSettings["pass"])
  28. {
  29. rsp.StatusCode = 403;
  30. rsp.Write("403 Access Denied");
  31. ctx.ApplicationInstance.CompleteRequest();
  32. return;
  33. }
  34. var url = qs["url"];
  35. if (string.IsNullOrEmpty(url))
  36. {
  37. rsp.StatusCode = 400;
  38. rsp.Write("400 Bad Request: Missing URL param");
  39. ctx.ApplicationInstance.CompleteRequest();
  40. return;
  41. }
  42. rsp.ContentType = "text/html";
  43. rsp.Write($"Download it - {url}<br/>");
  44. try
  45. {
  46. var http = new HttpClient();
  47. var r = http.GetAsync(url).Result;
  48. if (!r.IsSuccessStatusCode) throw new HttpException((int)r.StatusCode, r.ReasonPhrase);
  49. var fileName = r.Content.Headers.ContentDisposition?.FileName;
  50. if (string.IsNullOrWhiteSpace(fileName)) fileName = Path.GetFileName(url);
  51. if (string.IsNullOrWhiteSpace(fileName)) fileName = $"Download-{DateTime.Now:yyyyMMdd-HHmmssff}.bin";
  52. var start = DateTime.Now;
  53. rsp.Write($"Download start at {start}<br/>");
  54. var buf = r.Content.ReadAsByteArrayAsync().Result;
  55. var end = DateTime.Now;
  56. rsp.Write($"Download end at {end}<br/>");
  57. var len = buf.Length;
  58. rsp.Write($"Len: {len}<br/>");
  59. rsp.Write($"FileName: {fileName}<br/>");
  60. rsp.Write($"Download dur {end - start}<br/>");
  61. var saveTo = ctx.Server.MapPath("~/" + fileName);
  62. File.WriteAllBytes(saveTo, buf);
  63. rsp.Write($"File Saved<br/>");
  64. }
  65. catch (Exception exception)
  66. {
  67. rsp.StatusCode = 500;
  68. rsp.Write($"Error: {exception.Message}<br/>");
  69. }
  70. ctx.ApplicationInstance.CompleteRequest();
  71. }
  72. private class DownloadState
  73. {
  74. }
  75. public void Dispose()
  76. {
  77. }
  78. }
  79. }