using System; using System.Collections.Generic; using System.Net; using System.Threading.Tasks; using System.Web; namespace Sony.Filtr.API { public class ProxyAsyncHandler : HttpTaskAsyncHandler { public override async Task ProcessRequestAsync(HttpContext context) { string url = context.Request.QueryString["url"]; if (string.IsNullOrWhiteSpace(url)) { context.Response.StatusCode = (int) HttpStatusCode.NotFound; return; } var uri = new Uri(url); if (uri.Host != "userserve-ak.last.fm" && uri.Host != "img2-ak.lst.fm") throw new Exception("Proxy only enabled for http://userserve-ak.last.fm or http://img2-ak.lst.fm"); var webRequest = (HttpWebRequest)WebRequest.Create(url); webRequest.UserAgent = context.Request.UserAgent; webRequest.AllowAutoRedirect = true; if (context.Request.AcceptTypes != null) webRequest.Accept = context.Request.AcceptTypes.ToString(); DateTime ifModifiedSince; if (DateTime.TryParse(context.Request.Headers["If-Modified-Since"], out ifModifiedSince)) webRequest.IfModifiedSince = ifModifiedSince; foreach (string headerKey in context.Request.Headers) { if (!_restrictedHeaders.Contains(headerKey.ToLowerInvariant())) webRequest.Headers[headerKey] = context.Request.Headers[headerKey]; } webRequest.ContentType = context.Request.ContentType; webRequest.Method = context.Request.HttpMethod; HttpWebResponse webResponse; try { webResponse = await webRequest.GetResponseAsync() as HttpWebResponse; if (webResponse != null) { var responseStream = webResponse.GetResponseStream(); if (responseStream != null) await responseStream.CopyToAsync(context.Response.OutputStream); } } catch (WebException ex) { webResponse = ex.Response as HttpWebResponse; if (webResponse == null || ex.Status != WebExceptionStatus.ProtocolError) throw; } if (webResponse != null) { context.Response.ContentType = webResponse.ContentType; context.Response.StatusCode = (int)webResponse.StatusCode; context.Response.StatusDescription = webResponse.StatusDescription; foreach (string responseHeader in webResponse.Headers) { context.Response.Headers[responseHeader] = webResponse.Headers[responseHeader]; } } } private readonly List _restrictedHeaders = new List() { "accept", "connection", "content-length", "Content-type", "date", "expect", "host", "if-modified-since", "range", "referer", "transfer-encoding", "user-agent", "proxy-connection", }; } }