/// <summary> /// Try to return a file to client. Return false if file is not found /// </summary> /// <returns></returns> private static bool ReplyFile(IHttpResponseDelegate response, String filePath) { if (!File.Exists(filePath)) { return(false); } var ext = (Path.GetExtension(filePath).TrimOrNull() ?? ".").Substring(1).ToLower(); String contentType = ContentTypes.GetOrDefault(ext, "text/plain"); Reply(response, contentType, File.ReadAllBytes(filePath), contentType.StartsWith("image/"), null, null); return(true); }
public async Task GetAsync(HttpListenerContext context) { var fullpath = FindFile(context.Request.Url.LocalPath); if (fullpath == null) { throw new HttpException(404, "Not Found"); } var contentType = ContentTypes.GetOrDefault(Path.GetExtension(fullpath)); if (contentType == null) { throw new HttpException(404, "Not Found"); } if (contentType == PageContentType) { onpage(context); } try { //NOTE: Mono breaks keep-alive connection on disponsing HttpResponseStream //using(var outputStream = context.Response.OutputStream) using (var stream = new FileStream(fullpath, FileMode.Open, FileAccess.Read, FileShare.Read, 4096, FileOptions.SequentialScan | FileOptions.Asynchronous)) { context.Response.ContentLength64 = stream.Length; context.Response.ContentType = contentType; context.Response.AddHeader("Cache-Control", "private, max-age=" + MaxAge); context.Response.AddHeader("Accept-Ranges", "none"); await stream.CopyToAsync(context.Response.OutputStream); await context.Response.OutputStream.FlushAsync(); } } catch (FileNotFoundException) { throw new HttpException(404, "Not Found"); } }