public void Service(HttpListenerRequest request, HttpListenerResponse response) { Request = request; Response = response; try { if (OnPreService()) { OnService(); OnPostService(); } else if (Response.StatusCode == 200) { Server.CreateErrorServlet().Service(request, response); } } catch (Exception e) { Server.Log(e); } finally { try { Response.Close(); } catch { } } }
protected void Service(string resourceRootUrl, string resourceDir) { Response.Headers.Add("Accept-Ranges", "bytes"); if (resourceDir != null) { if (EnableCaching) { var etag = Request.Headers["If-None-Match"]; if (etag != null && etag.Equals(VersionNonce)) { Response.StatusCode = 304; return; } } var url = Request.Url.LocalPath; if (url.StartsWith(resourceRootUrl)) { url = UrlRelativeTo(url, resourceRootUrl); } var path = Path.GetFullPath(resourceDir + "/" + url); var ext = Path.GetExtension(path); if (!File.Exists(path) && Directory.Exists(path)) { path += "/index.html"; ext = ".html"; } if (ContentTypes.ContainsKey(ext) && File.Exists(path)) { Response.ContentType = ContentTypes[ext]; if (EnableCaching) { Response.AddHeader("ETag", VersionNonce); } int min = 0, max = int.MaxValue; var usingRange = false; var rangeHeader = Request.Headers["Range"]; if (rangeHeader != null && rangeHeader.StartsWith("bytes=")) { rangeHeader = rangeHeader.Substring("bytes=".Length); var split = rangeHeader.Split('-'); if (split.Length == 2) { usingRange = true; if (split[0].Length > 0) { int.TryParse(split[0], out min); } if (split[1].Length > 0) { int.TryParse(split[1], out max); } } } if (Request.HttpMethod != "HEAD") { Response.KeepAlive = true; Response.AddHeader("Connection", "keep-alive"); using (var stream = File.Open(path, FileMode.Open, FileAccess.Read, FileShare.Read)) { min = Math.Max(min, 0); max = Math.Min(max, (int)stream.Length - 1); try { if (usingRange) { Response.StatusCode = 206; Response.Headers.Add("Content-Range", string.Format("bytes {0}-{1}/{2}", min, max, stream.Length)); Response.ContentLength64 = max - min + 1; stream.Seek(min, SeekOrigin.Begin); } CopyTo(stream, Response.OutputStream, max - min + 1); } catch { return; } } } else { var info = new FileInfo(path); min = Math.Max(min, 0); max = Math.Min(max, (int)info.Length - 1); Response.ContentLength64 = max - min + 1; if (usingRange) { Response.StatusCode = 206; Response.Headers.Add("Content-Range", string.Format("bytes {0}-{1}/{2}", min, max, info.Length)); } } return; } } Server.CreateErrorServlet().Service(Request, Response); }