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 Sessions = new ConcurrentDictionary(); 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}
"); 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}
"); var buf = r.Content.ReadAsByteArrayAsync().Result; var end = DateTime.Now; rsp.Write($"Download end at {end}
"); var len = buf.Length; rsp.Write($"Len: {len}
"); rsp.Write($"FileName: {fileName}
"); rsp.Write($"Download dur {end - start}
"); var saveTo = ctx.Server.MapPath("~/" + fileName); File.WriteAllBytes(saveTo, buf); rsp.Write($"File Saved
"); } catch (Exception exception) { rsp.StatusCode = 500; rsp.Write($"Error: {exception.Message}
"); } ctx.ApplicationInstance.CompleteRequest(); } private class DownloadState { } public void Dispose() { } } }