public async Task IfRequestRateTooLargeException_ItHandlesTheException() { // Arrange // Options var optionsMock = new Mock <IOptions <ExceptionHandlerOptions> >(); optionsMock.Setup(o => o.Value).Returns(new ExceptionHandlerOptions()); // Request var requestMock = new Mock <HttpRequest>(); requestMock.Setup(x => x.Scheme).Returns("http"); requestMock.Setup(x => x.Host).Returns(new HostString("localhost")); requestMock.Setup(x => x.Path).Returns(new PathString("/FooBar")); requestMock.Setup(x => x.PathBase).Returns(new PathString("/")); requestMock.Setup(x => x.Method).Returns("GET"); requestMock.Setup(x => x.Body).Returns(new MemoryStream()); // Context var contextMock = new Mock <HttpContext>(); // Response var responseMock = new Mock <HttpResponse>(); responseMock.SetupAllProperties(); responseMock.SetupGet(y => y.Headers).Returns(new HeaderDictionary()); responseMock.SetupGet(y => y.Body).Returns(new MemoryStream()); responseMock.SetupGet(y => y.HttpContext).Returns(contextMock.Object); // Features var featuresCollection = new FeatureCollection(); featuresCollection.Set <IHttpResponseFeature>(new HttpResponseFeature()); // Context Setup contextMock.Setup(z => z.Request).Returns(requestMock.Object); contextMock.Setup(z => z.Response).Returns(responseMock.Object); contextMock.Setup(z => z.Features).Returns(featuresCollection); // Middleware var logRequestMiddleware = new GlobalInternalErrorHandlerMiddleware(next: NextTooManyRequests, options: optionsMock.Object); // Act await logRequestMiddleware.Invoke(contextMock.Object); // Assert responseMock.VerifySet(r500 => r500.StatusCode = 500); Assert.IsNotNull(featuresCollection.Get <IExceptionHandlerFeature>()); Assert.IsNotNull(featuresCollection.Get <IExceptionHandlerFeature>().Error); }
public void TestGetSet() { var features = new FeatureCollection(); var dummy0 = new Dummy(); var dummy1 = new Dummy(); var dummy2 = new Dummy(); features.Set <IDummy>(dummy0); features.Set <Dummy>(dummy1); features.Set <Dummy>(dummy2); Assert.Equal(features.Get <IDummy>(), dummy0); Assert.NotEqual(features.Get <Dummy>(), dummy1); Assert.Equal(features.Get <Dummy>(), dummy2); }
public void TestDefaultFeatures() { var defaultFeatues = new FeatureCollection(); var dummy0 = new Dummy(); var dummy1 = new Dummy(); defaultFeatues.Set <IDummy>(dummy0); defaultFeatues.Set <Dummy>(dummy1); var dummy = new Dummy(); var features = new FeatureCollection(defaultFeatues); features.Set <IDummy>(dummy); Assert.Equal(features.Get <IDummy>(), dummy); Assert.Equal(features.Get <Dummy>(), dummy1); }
public void TestIndexAndGetSet() { var features = new FeatureCollection(); var dummy0 = new Dummy(); var dummy1 = new Dummy(); var dummy2 = new Dummy(); features.Set <IDummy>(dummy0); features[typeof(Dummy)] = dummy1; Assert.Equal(features.Get <Dummy>(), dummy1); features.Set <Dummy>(dummy2); Assert.Equal(features.Get <IDummy>(), dummy0); Assert.NotEqual(features.Get <Dummy>(), dummy1); Assert.Equal(features.Get <Dummy>(), features[typeof(Dummy)]); Assert.Equal(features.Get <Dummy>(), dummy2); }
public void SetAndGet() { var features = new FeatureCollection(); Assert.Null(features.Get <Feature>()); var feature1 = new Feature(); features.Set(feature1); Assert.Same(feature1, features.Get <Feature>()); features.Set(default(Feature)); Assert.Null(features.Get <Feature>()); }
public void ParentAvailableIfNotSet() { var features1 = new FeatureCollection(); var feature1 = new Feature(); features1.Set(feature1); var features2 = new FeatureCollection(features1); Assert.Same(feature1, features2.Get <Feature>()); }
public void NestedDoesntAffectParent() { var features1 = new FeatureCollection(); var features2 = new FeatureCollection(features1); var feature1 = new Feature(); var feature2 = new Feature(); features1.Set(feature1); features2.Set(feature2); Assert.Same(feature1, features1.Get <Feature>()); Assert.Same(feature2, features2.Get <Feature>()); }
public Task StartAsync <TContext>(IHttpApplication <TContext> application, CancellationToken cancellationToken) { return(Task.Run(() => { Func <IDictionary <string, object>, Task> appFunc = async env => { var owinFeatures = new OwinFeatureCollection(env); var features = new FeatureCollection(owinFeatures); var owinHttpResponse = features.Get <IHttpResponseFeature>(); features.Set <IHttpResponseFeature>(new NoOnStartingHttpResponseFeature(owinHttpResponse)); var context = application.CreateContext(features); try { await application.ProcessRequestAsync(context); } catch (Exception ex) { application.DisposeContext(context, ex); throw; } application.DisposeContext(context, null); }; // Convert OWIN WebSockets to ASP.NET Core WebSockets appFunc = OwinWebSocketAcceptAdapter.AdaptWebSockets(appFunc); // Wrap this into a middleware handler that Fos can accept Func <IDictionary <string, object>, Func <IDictionary <string, object>, Task>, Task> middlewareHandler = async(env, next) => { await appFunc(env); if (next != null) { await next(env); } }; cgiServer = new FosSelfHost(builder => { builder.Use(middlewareHandler); }); cgiServer.Bind(IPAddress.Loopback, 9000); cgiServer.Start(true); }, cancellationToken)); }
/// <summary> /// Initializes a new instance of the <see cref="FtpConnection"/> class. /// </summary> /// <param name="socketAccessor">The accessor to get the socket used to communicate with the client.</param> /// <param name="options">The options for the FTP connection.</param> /// <param name="portOptions">The <c>PORT</c> command options.</param> /// <param name="connectionAccessor">The accessor to get the connection that is active during the <see cref="FtpCommandHandler.Process"/> method execution.</param> /// <param name="catalogLoader">The catalog loader for the FTP server.</param> /// <param name="serverCommandExecutor">The executor for server commands.</param> /// <param name="serviceProvider">The service provider for the connection.</param> /// <param name="secureDataConnectionWrapper">Wraps a data connection into an SSL stream.</param> /// <param name="sslStreamWrapperFactory">The SSL stream wrapper factory.</param> /// <param name="logger">The logger for the FTP connection.</param> /// <param name="loggerFactory">The logger factory.</param> public FtpConnection( TcpSocketClientAccessor socketAccessor, IOptions <FtpConnectionOptions> options, IOptions <PortCommandOptions> portOptions, IFtpConnectionAccessor connectionAccessor, IFtpCatalogLoader catalogLoader, IServerCommandExecutor serverCommandExecutor, IServiceProvider serviceProvider, SecureDataConnectionWrapper secureDataConnectionWrapper, ISslStreamWrapperFactory sslStreamWrapperFactory, ILogger <FtpConnection>?logger = null, ILoggerFactory?loggerFactory = null) { var socket = socketAccessor.TcpSocketClient ?? throw new InvalidOperationException("The socket to communicate with the client was not set"); ConnectionServices = serviceProvider; ConnectionId = "FTP-" + Guid.NewGuid().ToString("N"); _dataPort = portOptions.Value.DataPort; #pragma warning disable 612 _keepAlive = new FtpConnectionKeepAlive(this); #pragma warning restore 612 _idleCheck = new IdleCheck(this); var remoteEndPoint = _remoteEndPoint = (IPEndPoint)socket.Client.RemoteEndPoint; #pragma warning disable 618 RemoteAddress = new Address(remoteEndPoint.Address.ToString(), remoteEndPoint.Port); #pragma warning restore 618 var properties = new Dictionary <string, object?> { ["RemoteAddress"] = remoteEndPoint.ToString(), ["RemoteIp"] = remoteEndPoint.Address.ToString(), ["RemotePort"] = remoteEndPoint.Port, ["ConnectionId"] = ConnectionId, }; _loggerScope = logger?.BeginScope(properties); _socket = socket; _connectionAccessor = connectionAccessor; _serverCommandExecutor = serverCommandExecutor; _secureDataConnectionWrapper = secureDataConnectionWrapper; _serverCommandChannel = Channel.CreateBounded <IServerCommand>(new BoundedChannelOptions(3)); _logger = logger; var parentFeatures = new FeatureCollection(); var connectionFeature = new ConnectionFeature( (IPEndPoint)socket.Client.LocalEndPoint, remoteEndPoint); var secureConnectionFeature = new SecureConnectionFeature(); var applicationInputPipe = new Pipe(); var applicationOutputPipe = new Pipe(); var socketPipe = new DuplexPipe(_socketCommandPipe.Reader, _socketResponsePipe.Writer); var connectionPipe = new DuplexPipe(applicationOutputPipe.Reader, applicationInputPipe.Writer); var originalStream = socketAccessor.TcpSocketStream ?? socket.GetStream(); _streamReaderService = new ConnectionClosingNetworkStreamReader( originalStream, _socketCommandPipe.Writer, _cancellationTokenSource, loggerFactory?.CreateLogger($"{typeof(StreamPipeWriterService).FullName}.Socket.Receive")); _streamWriterService = new StreamPipeWriterService( originalStream, _socketResponsePipe.Reader, _cancellationTokenSource.Token, loggerFactory?.CreateLogger($"{typeof(StreamPipeWriterService).FullName}.Socket.Transmit")); _networkStreamFeature = new NetworkStreamFeature( new SecureConnectionAdapter( socketPipe, connectionPipe, sslStreamWrapperFactory, _cancellationTokenSource.Token, loggerFactory), applicationOutputPipe.Writer); parentFeatures.Set <IConnectionFeature>(connectionFeature); parentFeatures.Set <ISecureConnectionFeature>(secureConnectionFeature); parentFeatures.Set <IServerCommandFeature>(new ServerCommandFeature(_serverCommandChannel)); parentFeatures.Set <INetworkStreamFeature>(_networkStreamFeature); parentFeatures.Set <IFtpConnectionEventHost>(this); parentFeatures.Set <IFtpConnectionStatusCheck>(_idleCheck); #pragma warning disable 618 #pragma warning disable 612 parentFeatures.Set <IFtpConnectionKeepAlive>(_keepAlive); #pragma warning restore 612 #pragma warning restore 618 var features = new FeatureCollection(parentFeatures); #pragma warning disable 618 Data = new FtpConnectionData( options.Value.DefaultEncoding ?? Encoding.ASCII, features, catalogLoader); #pragma warning restore 618 Features = features; _authorizationInformationFeature = features.Get <IAuthorizationInformationFeature>(); _commandReader = ReadCommandsFromPipeline( applicationInputPipe.Reader, _ftpCommandChannel.Writer, _cancellationTokenSource.Token); }