Exemplo n.º 1
0
        public async Task SendAsync()
        {
            ApplyResponseHeaders(Constants.Status200Ok);
            string physicalPath = _fileInfo.PhysicalPath;
            var    sendFile     = _context.Features.Get <IHttpSendFileFeature>();

            if (sendFile != null && !string.IsNullOrEmpty(physicalPath))
            {
                // We don't need to directly cancel this, if the client disconnects it will fail silently.
                await sendFile.SendFileAsync(physicalPath, 0, _length, CancellationToken.None);

                return;
            }

            try
            {
                using (var readStream = _fileInfo.CreateReadStream())
                {
                    // Larger StreamCopyBufferSize is required because in case of FileStream readStream isn't going to be buffering
                    await StreamCopyOperation.CopyToAsync(readStream, _response.Body, _length, StreamCopyBufferSize, _context.RequestAborted);
                }
            }
            catch (OperationCanceledException ex)
            {
                _logger.LogWriteCancelled(ex);
                // Don't throw this exception, it's most likely caused by the client disconnecting.
                // However, if it was cancelled for any other reason we need to prevent empty responses.
                _context.Abort();
            }
        }
Exemplo n.º 2
0
    internal static async Task WriteFileAsync(HttpContext context, ReadOnlyMemory <byte> buffer, RangeItemHeaderValue?range, long rangeLength)
    {
        var outputStream = context.Response.Body;

        try
        {
            if (range is null)
            {
                await outputStream.WriteAsync(buffer, context.RequestAborted);
            }
            else
            {
                var from   = 0;
                var length = 0;

                checked
                {
                    // Overflow should throw
                    from   = (int)range.From !.Value;
                    length = (int)rangeLength;
                }

                await outputStream.WriteAsync(buffer.Slice(from, length), context.RequestAborted);
            }
        }
        catch (OperationCanceledException)
        {
            // Don't throw this exception, it's most likely caused by the client disconnecting.
            // However, if it was cancelled for any other reason we need to prevent empty responses.
            context.Abort();
        }
    }
Exemplo n.º 3
0
        public async Task Process(HttpContext context, WebSocket webSocket)
        {
            this.webSocket = webSocket;
            var buffer = new byte[1024 * 4];
            WebSocketReceiveResult result;

            do
            {
                result = await webSocket.ReceiveAsync(new ArraySegment <byte>(buffer), CancellationToken.None);

                if (result.MessageType == WebSocketMessageType.Text)
                {
                    string content = Encoding.UTF8.GetString(buffer, 0, result.Count);
                    if (content.Equals("ServerClose"))
                    {
                        await webSocket.CloseAsync(WebSocketCloseStatus.NormalClosure, "Closing from Server", CancellationToken.None);

                        return;
                    }
                    else if (content.Equals("ServerAbort"))
                    {
                        context.Abort();
                    }
                    await HandleKontomatikJson(content);
                }
            } while (!result.CloseStatus.HasValue);
            await webSocket.CloseAsync(result.CloseStatus.Value, result.CloseStatusDescription, CancellationToken.None);
        }
Exemplo n.º 4
0
        private static async Task SendFileAsync(this HttpResponse response, FileInfo file)
        {
            HttpContext context = response.HttpContext;

            string physicalPath = file.FullName;
            var    length       = file.Length;
            var    sendFile     = context.Features.Get <IHttpSendFileFeature>();

            if (sendFile != null && !string.IsNullOrEmpty(physicalPath))
            {
                await sendFile.SendFileAsync(physicalPath, 0, length, CancellationToken.None);

                return;
            }

            try
            {
                using (var readStream = file.OpenRead())
                {
                    await StreamCopyOperation.CopyToAsync(readStream, response.Body, length, 64 * 1024, context.RequestAborted);
                }
            }
            catch (OperationCanceledException)
            {
                context.Abort();
            }
        }
Exemplo n.º 5
0
            // FileResultExecutorBase.WriteFileAsync with custom bufferSize
            private async Task WriteFileCoreAsync(HttpContext context, Stream fileStream, RangeItemHeaderValue range, long rangeLength)
            {
                var outputStream = context.Response.Body;

                await using (fileStream)
                {
                    try
                    {
                        if (range == null)
                        {
                            await StreamCopyOperation.CopyToAsync(fileStream, outputStream, count : null, bufferSize : _bufferSize, cancel : context.RequestAborted);
                        }
                        else
                        {
                            fileStream.Seek(range.From.Value, SeekOrigin.Begin);
                            await StreamCopyOperation.CopyToAsync(fileStream, outputStream, rangeLength, _bufferSize, context.RequestAborted);
                        }
                    }
                    catch (OperationCanceledException)
                    {
                        // Don't throw this exception, it's most likely caused by the client disconnecting.
                        // However, if it was cancelled for any other reason we need to prevent empty responses.
                        context.Abort();
                    }
                }
            }
Exemplo n.º 6
0
        public async Task Invoke(HttpContext context)
        {
            Request request = Repository.AddRequest(context.Request);

            Task.Delay(Configuration.CostKeepingTime * 60 * 100).ContinueWith((t) => Repository.RemoveRequest(request));
            ClientIp clientIp = request.ClientIp;

            if (clientIp.IsWhiteListed)
            {
                await _next.Invoke(context);
            }
            else
            {
                if (clientIp.IsBlackListed || clientIp.CurrentRequestCosts > Configuration.BlockingLimitPerIp)
                {
                    _logger.LogError(0, $"Request blocked from: {clientIp.Ip}");
                    request.IsBlocked = true;
                    request.Costs     = Configuration.BlockingLimitPerIp;
                    context.Abort();
                    return;
                }
                Task requestTask = _next.Invoke(context);
                request.Costs = CalculateStaticCosts(request);
                await requestTask;
                CalculateDynamicRequestCosts(context, request);
                foreach (ICostMultiplier multiplier in Configuration.CostMultipliers)
                {
                    request.Costs = request.Costs * (int)multiplier.Calculate(request);
                }
                //Task.Run(() => CheckBlocking(request));
                _logger.LogInformation(0,
                                       $"Request from: {clientIp.Ip}, Costs: {request.Costs}, Costs for IP: {clientIp.CurrentRequestCosts}, Duration: {DateTime.Now.Subtract(request.Time).Milliseconds} ms");
            }
        }
        private async Task Echo(HttpContext context, WebSocket webSocket, ILogger logger)
        {
            var buffer = new byte[1024 * 4];
            var result = await webSocket.ReceiveAsync(new ArraySegment <byte>(buffer), CancellationToken.None);

            while (!result.CloseStatus.HasValue)
            {
                string content = "<<binary>>";
                if (result.MessageType == WebSocketMessageType.Text)
                {
                    content = Encoding.UTF8.GetString(buffer, 0, result.Count);
                    if (content.Equals("ServerClose"))
                    {
                        await webSocket.CloseAsync(WebSocketCloseStatus.NormalClosure, "Closing from Server", CancellationToken.None);

                        logger.LogDebug($"Sent Frame Close: {WebSocketCloseStatus.NormalClosure} Closing from Server");
                        return;
                    }
                    else if (content.Equals("ServerAbort"))
                    {
                        context.Abort();
                    }
                }

                await webSocket.SendAsync(new ArraySegment <byte>(buffer, 0, result.Count), result.MessageType, result.EndOfMessage, CancellationToken.None);

                logger.LogDebug($"Sent Frame {result.MessageType}: Len={result.Count}, Fin={result.EndOfMessage}: {content}");

                result = await webSocket.ReceiveAsync(new ArraySegment <byte>(buffer), CancellationToken.None);
            }
            await webSocket.CloseAsync(result.CloseStatus.Value, result.CloseStatusDescription, CancellationToken.None);
        }
    public async Task InvokeAsync(HttpContext context, RequestDelegate next)
    {
        try
        {
            if (await _fileServer.TryServeFile(context, CancellationToken.None))
            {
                return;
            }
        }
        catch (OperationCanceledException)
        {
            if (context.Response.HasStarted)
            {
                context.Abort();
            }
            else
            {
                context.Response.StatusCode = StatusCodes.Status408RequestTimeout;
            }

            return;
        }

        await next.Invoke(context);
    }
Exemplo n.º 9
0
        private async Task SendAsync(HttpContext context, StaticFileInfo fileInfo)
        {
            SetCompressionMode(context);
            context.Response.StatusCode    = 200;
            context.Response.ContentLength = fileInfo.File.Length;
            context.Response.ContentType   = fileInfo.ContentType;

            ResponseHeaders headers = context.Response.GetTypedHeaders();

            headers.LastModified = fileInfo.File.LastModified;
            headers.ETag         = fileInfo.EntityTagHeader;
            headers.Headers[HeaderNames.AcceptRanges] = "bytes";

            try
            {
                await context.Response.SendFileAsync(
                    fileInfo.File,
                    0,
                    fileInfo.File.Length,
                    context.RequestAborted);
            }
            catch (OperationCanceledException)
            {
                context.Abort();
            }
        }
Exemplo n.º 10
0
        private async Task WriteFileAsync(HttpContext context, FileAuthorizeResult result, FileInfo fileInfo)
        {
            var response = context.Response;
            var sendFile = response.HttpContext.Features.Get <IHttpSendFileFeature>();

            if (sendFile != null)
            {
                await sendFile.SendFileAsync(fileInfo.FullName, 0L, null, default(CancellationToken));

                return;
            }


            using (var fileStream = new FileStream(
                       fileInfo.FullName,
                       FileMode.Open,
                       FileAccess.Read,
                       FileShare.ReadWrite,
                       BufferSize,
                       FileOptions.Asynchronous | FileOptions.SequentialScan))
            {
                try
                {
                    await StreamCopyOperation.CopyToAsync(fileStream, context.Response.Body, count : null, bufferSize : BufferSize, cancel : context.RequestAborted);
                }
                catch (OperationCanceledException)
                {
                    // Don't throw this exception, it's most likely caused by the client disconnecting.
                    // However, if it was cancelled for any other reason we need to prevent empty responses.
                    context.Abort();
                }
            }
        }
Exemplo n.º 11
0
        public async Task PostExport()
        {
            using (ContextPool.AllocateOperationContext(out DocumentsOperationContext context))
            {
                var operationId       = GetLongQueryString("operationId", false) ?? Database.Operations.GetNextOperationId();
                var startDocumentEtag = GetLongQueryString("startEtag", false) ?? 0;

                var stream = TryGetRequestFromStream("DownloadOptions") ?? RequestBodyStream();


                DatabaseSmugglerOptionsServerSide options;
                using (context.GetManagedBuffer(out var buffer))
                {
                    var firstRead = await stream.ReadAsync(buffer.Buffer.Array, buffer.Buffer.Offset, buffer.Buffer.Count);

                    buffer.Used  = 0;
                    buffer.Valid = firstRead;
                    if (firstRead != 0)
                    {
                        var blittableJson = await context.ParseToMemoryAsync(stream, "DownloadOptions", BlittableJsonDocumentBuilder.UsageMode.None, buffer);

                        options = JsonDeserializationServer.DatabaseSmugglerOptions(blittableJson);
                    }
                    else
                    {
                        // no content, we'll use defaults
                        options = new DatabaseSmugglerOptionsServerSide();
                    }
                }

                ApplyBackwardCompatibility(options);

                var token = CreateOperationToken();

                var fileName = options.FileName;
                if (string.IsNullOrEmpty(fileName))
                {
                    fileName = $"Dump of {context.DocumentDatabase.Name} {SystemTime.UtcNow.ToString("yyyy-MM-dd HH-mm", CultureInfo.InvariantCulture)}";
                }

                var contentDisposition = "attachment; filename=" + Uri.EscapeDataString(fileName) + ".ravendbdump";
                HttpContext.Response.Headers["Content-Disposition"] = contentDisposition;

                try
                {
                    await Database.Operations.AddOperation(
                        Database,
                        "Export database: " + Database.Name,
                        Operations.OperationType.DatabaseExport,
                        onProgress => Task.Run(() => ExportDatabaseInternal(options, startDocumentEtag, onProgress, context, token), token.Token), operationId, token : token);
                }
                catch (Exception)
                {
                    HttpContext.Abort();
                }
            }
        }
Exemplo n.º 12
0
        public void WhenConnectionIsClosedByClient_ConnectionClosedEventShouldBeRaised()
        {
            using var eventMonitor = _sut.Monitor();

            _context.Abort();

            eventMonitor.Should().Raise(nameof(_sut.ConnectionClosed))
            .WithSender(_sut);
        }
Exemplo n.º 13
0
        Task closeConnection(HttpContext httpContext)
        {
            return(Task.Run(() =>
            {
                Task.Delay(1000).Wait();

                httpContext.Abort();
            }));
        }
        private void DeadlineExceeded(object state)
        {
            DeadlineExceeded(_logger, (TimeSpan)state);

            StatusCore = new Status(StatusCode.DeadlineExceeded, "Deadline Exceeded");

            // TODO(JamesNK): I believe this sends a RST_STREAM with INTERNAL_ERROR. Grpc.Core sends NO_ERROR
            HttpContext.Abort();
        }
Exemplo n.º 15
0
        private async Task ProcessWebSocketMessages(HttpContext context, WebSocket webSocket, IRepository repository, ILogger logger)
        {
            var buffer = new byte[1024 * 4];
            int bytesToSend;
            var result = await webSocket.ReceiveAsync(new ArraySegment <byte>(buffer), CancellationToken.None);

            bytesToSend = result.Count;
            LogFrame(logger, result, buffer);

            while (!result.CloseStatus.HasValue)
            {
                // If the client send "ServerClose", then they want a server-originated close to occur
                string content = "<<binary>>";
                if (result.MessageType == WebSocketMessageType.Text)
                {
                    content = Encoding.UTF8.GetString(buffer, 0, result.Count);

//                    repository.Add(new RepositoryItem { Created = DateTime.Now, Message = content });

                    if (content.Equals("ServerClose"))
                    {
                        await webSocket.CloseAsync(WebSocketCloseStatus.NormalClosure, "Closing from Server", CancellationToken.None);

                        logger.LogDebug($"Sent Frame Close: {WebSocketCloseStatus.NormalClosure} Closing from Server");
                        return;
                    }
                    else if (content.Equals("ServerAbort"))
                    {
                        context.Abort();
                    }
                    else if (content.Equals("Feed"))
                    {
                        StringBuilder sb = new StringBuilder();

                        foreach (var item in repository.GetAll())
                        {
                            sb.Append(item.Message);
                        }

                        byte[] bytes = Encoding.UTF8.GetBytes(sb.ToString());
                        bytes.CopyTo(buffer, 0);
                        bytesToSend = bytes.Length;
                    }
                }

                await webSocket.SendAsync(new ArraySegment <byte>(buffer, 0, bytesToSend), result.MessageType, result.EndOfMessage, CancellationToken.None);

                logger.LogDebug($"Sent Frame {result.MessageType}: Len={result.Count}, Fin={result.EndOfMessage}: {content}");

                result = await webSocket.ReceiveAsync(new ArraySegment <byte>(buffer), CancellationToken.None);

                bytesToSend = result.Count;
                LogFrame(logger, result, buffer);
            }

            await webSocket.CloseAsync(result.CloseStatus.Value, result.CloseStatusDescription, CancellationToken.None);
        }
Exemplo n.º 16
0
        public static Task RejectAsync([NotNull] this HttpContext context)
        {
            if (context is null)
            {
                throw new ArgumentNullException(nameof(context));
            }

            context.Response.SetStatusCode(HttpStatusCode.ServiceUnavailable);
            context.Abort();
            return(Task.CompletedTask);
        }
Exemplo n.º 17
0
 static async Task CentaurusWebSocketHandler(HttpContext context, Func <Task> next)
 {
     if (Global.AppState == null || ValidApplicationStates.Contains(Global.AppState.State))
     {
         using (var webSocket = await context.WebSockets.AcceptWebSocketAsync())
             await ConnectionManager.OnNewConnection(webSocket, context.Connection.RemoteIpAddress.ToString());
     }
     else
     {
         context.Abort();
     }
 }
Exemplo n.º 18
0
    public async Task Invoke(HttpContext context)
    {
        if (enableAuthCheck &&
            protectedControllers.Any(c => context.Request.Path.Value.ToLower().Contains(c)) &&
            (!context.Request.Headers.Any(h => h.Key == "PraxisAuthKey" && h.Value == ServerAuthKey) && !context.Request.Query.Any(q => q.Key == "PraxisAuthKey" && q.Value == ServerAuthKey)))
        {
            context.Abort();
            return;
        }

        await this._next.Invoke(context).ConfigureAwait(false);
    }
Exemplo n.º 19
0
        public async Task Invoke(HttpContext context)
        {
            bool isAlllowed = whitelistedIps.Any(_ip => _ip.SequenceEqual(context.Connection.RemoteIpAddress.GetAddressBytes()));

            if (isAlllowed)
            {
                await nextRequest.Invoke(context);
            }

            else
            {
                context.Abort();
            }
        }
Exemplo n.º 20
0
        private async Task Echo(HttpContext context, IWebSocketConnection webSocket, ILogger logger)
        {
            var lastFrameOpcode = WebSocketOpcode.Continuation;
            var closeResult     = await webSocket.ExecuteAsync(frame =>
            {
                if (frame.Opcode == WebSocketOpcode.Ping || frame.Opcode == WebSocketOpcode.Pong)
                {
                    // Already handled
                    return(Task.CompletedTask);
                }

                LogFrame(logger, lastFrameOpcode, ref frame);

                // If the client send "ServerClose", then they want a server-originated close to occur
                string content = "<<binary>>";
                if (frame.Opcode == WebSocketOpcode.Text)
                {
                    // Slooooow
                    content = Encoding.UTF8.GetString(frame.Payload.ToArray());
                    if (content.Equals("ServerClose"))
                    {
                        logger.LogDebug($"Sending Frame Close: {WebSocketCloseStatus.NormalClosure} Closing from Server");
                        return(webSocket.CloseAsync(new WebSocketCloseResult(WebSocketCloseStatus.NormalClosure, "Closing from Server")));
                    }
                    else if (content.Equals("ServerAbort"))
                    {
                        context.Abort();
                    }
                }

                if (frame.Opcode != WebSocketOpcode.Continuation)
                {
                    lastFrameOpcode = frame.Opcode;
                }
                logger.LogDebug($"Sending {frame.Opcode}: Len={frame.Payload.Length}, Fin={frame.EndOfMessage}: {content}");
                return(webSocket.SendAsync(frame));
            });

            if (webSocket.State == WebSocketConnectionState.CloseReceived)
            {
                // Close the connection from our end
                await webSocket.CloseAsync(WebSocketCloseStatus.NormalClosure);

                logger.LogDebug("Socket closed");
            }
            else if (webSocket.State != WebSocketConnectionState.Closed)
            {
                logger.LogError("WebSocket closed but not closed?");
            }
        }
Exemplo n.º 21
0
            static async Task CentaurusWebSocketHandler(HttpContext context, Func <Task> next)
            {
                var centaurusContext = context.RequestServices.GetService <AlphaContext>();

                if (centaurusContext.AppState == null || ValidApplicationStates.Contains(centaurusContext.AppState.State))
                {
                    using (var webSocket = await context.WebSockets.AcceptWebSocketAsync())
                        await centaurusContext.ConnectionManager.OnNewConnection(webSocket, context.Connection.RemoteIpAddress.ToString());
                }
                else
                {
                    context.Abort();
                }
            }
Exemplo n.º 22
0
        public async Task PostExport()
        {
            DocumentsOperationContext context;

            using (ContextPool.AllocateOperationContext(out context))
                using (context.OpenReadTransaction())
                {
                    var operationId = GetIntValueQueryString("operationId", required: false);

                    var stream = TryGetRequestFormStream("DownloadOptions") ?? RequestBodyStream();

                    var blittableJson = await context.ReadForMemoryAsync(stream, "DownloadOptions");

                    var options = JsonDeserializationServer.DatabaseSmugglerOptions(blittableJson);

                    var exporter = new SmugglerExporter(Database, options);
                    var token    = CreateOperationToken();

                    var fileName = exporter.Options.FileName;
                    if (string.IsNullOrEmpty(fileName))
                    {
                        fileName = $"Dump of {context.DocumentDatabase.Name} {SystemTime.UtcNow.ToString("yyyy-MM-dd HH-mm", CultureInfo.InvariantCulture)}";
                    }

                    var contentDisposition = "attachment; filename=" + Uri.EscapeDataString(fileName) + ".ravendbdump";
                    HttpContext.Response.Headers["Content-Disposition"] = contentDisposition;

                    if (operationId.HasValue)
                    {
                        try
                        {
                            await
                            Database.Operations.AddOperation("Export database: " + Database.Name,
                                                             DatabaseOperations.PendingOperationType.DatabaseExport,
                                                             onProgress =>
                                                             Task.Run(() => ExportDatabaseInternal(context, exporter, onProgress, token),
                                                                      token.Token), operationId.Value, token);
                        }
                        catch (Exception)
                        {
                            HttpContext.Abort();
                        }
                    }
                    else
                    {
                        ExportDatabaseInternal(context, exporter, null, token);
                    }
                }
        }
Exemplo n.º 23
0
        public async Task Invoke(HttpContext httpContext)
        {
            string accessToken = httpContext.Request.Headers["Authorization"];
            var    client      = _httpClientFactory.CreateClient("laravel");

            client.DefaultRequestHeaders.TryAddWithoutValidation("Authorization", accessToken);
            var res = await client.GetAsync("api/user");

            if (!res.IsSuccessStatusCode)
            {
                httpContext.Abort();
            }
            var user = (await res.Content.ReadAsAsync <User>());

            if (user == null)
            {
                httpContext.Abort();
            }

            Console.WriteLine(httpContext.User.ToString());


            await _next(httpContext);
        }
Exemplo n.º 24
0
        private static void ResetOrAbort(HttpContext context, bool isCancelled)
        {
            var resetFeature = context.Features.Get <IHttpResetFeature>();

            if (resetFeature != null)
            {
                // https://tools.ietf.org/html/rfc7540#section-7
                const int Cancelled     = 2;
                const int InternalError = 8;
                resetFeature.Reset(isCancelled ? Cancelled : InternalError);
                return;
            }

            context.Abort();
        }
Exemplo n.º 25
0
        public async Task InvokeAsync(HttpContext context)
        {
            Console.WriteLine("\n ----- Antes ----- \n");

            bool abort = context.Request.Path.Equals("/abort");

            if (abort)
            {
                context.Abort();
            }

            await this._next(context);

            Console.WriteLine("\n ----- Depois ----- \n");
        }
Exemplo n.º 26
0
        public async Task InvokeAsync(HttpContext context, UserManager <ApplicationUser> userManager)
        {
            var user = await userManager.GetUserAsync(context.User);

            if (user is not null &&
                (user.IsAdmin != context.User.IsInRole("GroupAdmin") ||
                 user.GroupId.ToString() != context.User.Claims.Single(c => c.Type == "household").Value))
            {
                await context.Response.WriteAsJsonAsync(new ForbidResult());

                context.Abort();
                return;
            }

            await _next(context);
        }
Exemplo n.º 27
0
        public async Task InvokeAsync(HttpContext context)
        {
            if (IsDisabled(context))
            {
                await next(context);

                return;
            }

            var info       = FlowingContext.Globals.Get <IRequestInfo>();
            var properties = BuildThrottlingProperties(context, info);

            using (var result = await provider.ThrottleAsync(properties, info?.RemainingTimeout))
            {
                if (context.RequestAborted.IsCancellationRequested)
                {
                    LogConnectionAlreadyAborted(context, info);
                    return;
                }

                if (result.Status == ThrottlingStatus.Passed)
                {
                    if (result.WaitTime >= LongThrottlingWaitTime)
                    {
                        LogWaitTime(context, info, result);
                    }

                    await next(context);

                    return;
                }

                LogFailure(context, info, result);

                if (ShouldAbortConnection(context, result))
                {
                    LogAbortingConnection();
                    context.Abort();
                }
                else
                {
                    context.Response.StatusCode            = options.RejectionResponseCode;
                    context.Response.Headers.ContentLength = 0L;
                }
            }
        }
Exemplo n.º 28
0
    public static async Task StreamAsync(this IEventStreamer eventStreamer, String topic, HttpContext httpContext)
    {
        var buffer    = new ArraySegment <Byte>(new Byte[4096]);
        var webSocket = await httpContext.WebSockets.AcceptWebSocketAsync();

        await eventStreamer.StreamAsync(topic, httpContext.RequestAborted, async message =>
        {
            await webSocket.SendTextAsync(message);

            var receiveResult = await webSocket.ReceiveAsync(buffer, httpContext.RequestAborted);

            if (receiveResult.CloseStatus.HasValue)
            {
                httpContext.Abort();
            }
        });
    }
Exemplo n.º 29
0
        private async Task ServeResponse()
        {
            var fileInfo = _fileProvider.GetFileInfo(_selectedVariant !.FileName);

            if (fileInfo == null)
            {
                // TODO is "Not Found" really the right logic here?
                // We are not finding a file that should be there on the server, and the fact that it isn't
                // is more indicative of a misconfiguration or inconsistent server deployment.
                await RespondNotFound();

                return;
            }

            _response.StatusCode = StatusCodes.Status200OK;
            SetFileHeaders();

            // do not actually send an entity in response to a HEAD request
            if (IsHead)
            {
                return;
            }

            if (fileInfo.PhysicalPath != null)
            {
                var sendFile = _context.Features.Get <IHttpResponseBodyFeature>();
                if (sendFile != null)
                {
                    await sendFile.SendFileAsync(fileInfo.PhysicalPath, 0, _selectedVariant.Size);

                    return;
                }
            }

            try
            {
                await using (var readStream = fileInfo.CreateReadStream())
                {
                    await readStream.CopyToAsync(_response.Body, 16384, _context.RequestAborted);
                }
            }
            catch (OperationCanceledException)
            {
                _context.Abort();
            }
        }
Exemplo n.º 30
0
        private async Task SendMessagesAsync(HttpContext context, WebSocket webSocket, ILogger logger)
        {
            var buffer = new byte[4096];
            WebSocketReceiveResult result = await webSocket.ReceiveAsync(new ArraySegment <byte>(buffer), CancellationToken.None);

            while (!result.CloseStatus.HasValue)
            {
                if (result.MessageType == WebSocketMessageType.Text)
                {
                    string content = Encoding.UTF8.GetString(buffer, 0, result.Count);
                    if (content.StartsWith("REQUESTMESSAGES:"))
                    {
                        string message = content.Substring("REQUESTMESSAGES:".Length);
                        for (int i = 0; i < 10; i++)
                        {
                            string messageToSend = $"{message} - {i}";
                            if (i == 9)
                            {
                                messageToSend += ";EOS"; // send end of sequence to not let the client wait for another message
                            }
                            byte[] sendBuffer = Encoding.UTF8.GetBytes(messageToSend);
                            await webSocket.SendAsync(new ArraySegment <byte>(sendBuffer), WebSocketMessageType.Text, endOfMessage : true, CancellationToken.None);

                            logger.LogDebug("sent message {0}", messageToSend);
                            await Task.Delay(1000);
                        }
                    }

                    if (content.Equals("SERVERCLOSE"))
                    {
                        await webSocket.CloseAsync(WebSocketCloseStatus.NormalClosure, "Bye for now", CancellationToken.None);

                        logger.LogDebug("client sent close request, socket closing");
                        return;
                    }
                    else if (content.Equals("SERVERABORT"))
                    {
                        context.Abort();
                    }
                }

                result = await webSocket.ReceiveAsync(buffer, CancellationToken.None);
            }
        }