123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104 |
- using System;
- using System.Collections.Concurrent;
- using System.Collections.Generic;
- using System.Configuration;
- using System.EnterpriseServices;
- using System.IO;
- using System.Linq;
- using System.Net;
- using System.Net.Http;
- using System.Web;
- using System.Web.Services.Configuration;
- namespace WebGet
- {
- public class WebGetModule : IHttpModule
- {
- private static readonly ConcurrentDictionary<string, DownloadState> Sessions = new ConcurrentDictionary<string, DownloadState>();
- public void Init(HttpApplication context)
- {
- context.PostMapRequestHandler += ContextOnPostMapRequestHandler;
- }
- private void ContextOnPostMapRequestHandler(object sender, EventArgs e)
- {
- var ctx = HttpContext.Current;
- var req = ctx.Request;
- var qs = req.QueryString;
- var rsp = ctx.Response;
- if (qs["pass"] != ConfigurationManager.AppSettings["pass"])
- {
- rsp.StatusCode = 403;
- rsp.Write("403 Access Denied");
- ctx.ApplicationInstance.CompleteRequest();
- return;
- }
- var url = qs["url"];
- if (string.IsNullOrEmpty(url))
- {
- rsp.StatusCode = 400;
- rsp.Write("400 Bad Request: Missing URL param");
- ctx.ApplicationInstance.CompleteRequest();
- return;
- }
- rsp.ContentType = "text/html";
- rsp.Write($"Download it - {url}<br/>");
- try
- {
- var http = new HttpClient();
- var r = http.GetAsync(url).Result;
- if (!r.IsSuccessStatusCode) throw new HttpException((int)r.StatusCode, r.ReasonPhrase);
- var fileName = r.Content.Headers.ContentDisposition?.FileName;
- if (string.IsNullOrWhiteSpace(fileName)) fileName = Path.GetFileName(url);
- if (string.IsNullOrWhiteSpace(fileName)) fileName = $"Download-{DateTime.Now:yyyyMMdd-HHmmssff}.bin";
- var start = DateTime.Now;
- rsp.Write($"Download start at {start}<br/>");
- var buf = r.Content.ReadAsByteArrayAsync().Result;
- var end = DateTime.Now;
- rsp.Write($"Download end at {end}<br/>");
- var len = buf.Length;
- rsp.Write($"Len: {len}<br/>");
- rsp.Write($"FileName: {fileName}<br/>");
- rsp.Write($"Download dur {end - start}<br/>");
- var saveTo = ctx.Server.MapPath("~/" + fileName);
- File.WriteAllBytes(saveTo, buf);
- rsp.Write($"File Saved<br/>");
- }
- catch (Exception exception)
- {
- rsp.StatusCode = 500;
- rsp.Write($"Error: {exception.Message}<br/>");
- }
- ctx.ApplicationInstance.CompleteRequest();
- }
- private class DownloadState
- {
- }
- public void Dispose()
- {
- }
- }
- }
|