Ejemplo n.º 1
0
        public async Task <bool> ServeAsync(IHttpRequest request, IHttpResponse response)
        {
            // Alter the header to indicate that we accept range requests;
            response.Header["Accept-Ranges"] = "bytes";
            try
            {
                // Handle the request if client requested range
                if (IsGetOrHead(request) &&
                    request.Header.ContainsKey(HttpKeys.Range) &&
                    _staticFileServer.TryResolve(request, out string resolvedFile))
                {
                    await ServeRangeContentAsync(request, response, resolvedFile);

                    return(true);
                }
                // Else, we won't be serving range content for this request,
                // leave it untouched.
                return(false);
            }
            catch (StaticRangeNotSatisfiableException) {
                // Bad range requested by the client,
                // We'll handle this
                await response.Return416Async();

                return(true);
            }
        }
Ejemplo n.º 2
0
        public async Task <bool> ServeAsync(
            IHttpRequest request,
            IHttpResponse response)
        {
            // Early exit for non GET/HEAD request
            if (request.Header.Method != HttpRequestMethod.GET &&
                request.Header.Method != HttpRequestMethod.HEAD)
            {
                return(false);
            }

            // Early exit if the request is not for a file
            if (false == _fileServer.TryResolve(request, out string resolvedPathToFile))
            {
                return(false);
            }

            // Now write the header and contents
            response.Header[HttpKeys.ContentType] =
                _fileServer.GetContentTypeHeader(resolvedPathToFile);
            using (var fs = _fileServer.OpenRead(resolvedPathToFile))
            {
                response.Header[HttpKeys.ContentLength] = fs.Length.ToString(CultureInfo.InvariantCulture);

                // Write body (only for GET request)
                if (request.Header.Method == HttpRequestMethod.GET)
                {
                    await fs.CopyToAsync(response.Body, _tcpSettings.ReadWriteBufferSize);
                }
                // For HEAD request, we are not sending the body,
                // Immediatly flush the header to prevent Content-length
                // validation on body upon completion of this request.
                else
                {
                    await response.SendHeaderAsync();
                }
            }

            // Return true, as we have served the content
            return(true);
        }