Пример #1
0
        private async Task ProcessRequestAsync(HttpContextBase context)
        {
            var diagnosticService = _configuration.DiagnosticService;

            await diagnosticService.EmitAsync(
                new HttpEventBuilder(this, HttpEventType.HttpRequestReceived)
            {
                Remote = context.Request.UserHostAddress,
                Uri    = context.Request.Url,
                Method = context.Request.HttpMethod
            }.Build());

            var resourceRequest  = new HttpRequestAdapter(context.Request, context.User);
            var resourceResponse = new HttpResponseAdapter(context.Response);

            try
            {
                await _resourceRouter.Route(resourceRequest, resourceResponse);
            }
            catch (Exception ex)
            {
                var exceptionHandler = new HttpExceptionHandler(resourceRequest, resourceResponse, diagnosticService);
                exceptionHandler.HandleException(ex);
            }

            await diagnosticService.EmitAsync(
                new HttpEventBuilder(this, HttpEventType.HttpRequestReceived)
            {
                Remote = context.Request.UserHostAddress,
                Uri    = context.Request.Url,
                Method = context.Request.HttpMethod,
                Status = context.Response.StatusCode
            }.Build());
        }
Пример #2
0
 public static void ProcessRequest(HttpContext context, HttpExceptionHandler exceptionHandler)
 {
     if (!ProcessRequest(context))
     {
         exceptionHandler(context.ApplicationInstance.Server.GetLastError() as HttpException);
     }
 }
Пример #3
0
        private static void _Main(string[] args)
        {
            var server = new WebServer("http://*****:*****@"C:\\Users\\jose.correa\\Unosquare\\wwwroot", true);
            server.RunAsync();

            Console.WriteLine("Hello World!");
            Console.ReadLine();
        }
Пример #4
0
        private async Task HandlePlatibusRequest(HttpContext context)
        {
            await _diagnosticService.EmitAsync(
                new HttpEventBuilder(this, HttpEventType.HttpRequestReceived)
            {
                Remote = context.Connection.RemoteIpAddress?.ToString(),
                Uri    = context.Request.GetUri(),
                Method = context.Request.Method
            }.Build());

            var resourceRequest  = new HttpRequestAdapter(context.Request);
            var resourceResponse = new HttpResponseAdapter(context.Response);

            try
            {
                await _resourceRouter.Route(resourceRequest, resourceResponse);
            }
            catch (Exception ex)
            {
                var exceptionHandler = new HttpExceptionHandler(resourceRequest, resourceResponse, _diagnosticService);
                exceptionHandler.HandleException(ex);
            }

            await _diagnosticService.EmitAsync(
                new HttpEventBuilder(this, HttpEventType.HttpResponseSent)
            {
                Remote = context.Connection.RemoteIpAddress?.ToString(),
                Uri    = context.Request.GetUri(),
                Method = context.Request.Method,
                Status = context.Response.StatusCode
            }.Build());
        }
Пример #5
0
        private static void Main(string[] args)
        {
            var server = new WebServer("http://*****:*****@"C:\\Unosquare\\wwroot", true);
            //server.WithZipFile()// Zip is always inmutable.
            //server.WithEmbeddedResources
            //configurations must be called before runAsync.
            server.RunAsync();

            Console.WriteLine("Hello World!");
            Console.ReadLine();
        }
        public async Task SendAsync_WhenInnerHandlerThrowsAnException_ShouldLogErrorMessage()
        {
            //Arrange
            var exceptionMessage = "ExceptionMessage";
            var dummyHandlerForExceptionThrowing = new DummyHandler(() =>
                                                                    throw new Exception(exceptionMessage));

            var sut = new HttpExceptionHandler(_loggerMock.Object)
            {
                InnerHandler = dummyHandlerForExceptionThrowing
            };

            var httpClientMock = new HttpClient(sut)
            {
                BaseAddress = new Uri("http://localhost")
            };

            //Act
            Assert.ThrowsAsync <Exception>(async() =>
                                           await httpClientMock.SendAsync(Mock.Of <HttpRequestMessage>(), new CancellationToken()));

            //Assert
            _loggerMock.Verify(x =>
                               x.Write(LogLevel.Error, $"{EventCodes.ErrorCallingBankApi} - {exceptionMessage}"),
                               Times.Once);
        }
        public void WhenHandlingUnauthorizedException_ReturnMessageAndUnauthorizedStatusCode()
        {
            HttpExceptionHandler test   = GetHttpExceptionHandlerWithMockLoggerFactory();
            HttpExceptionResult  result = test.Handle(new UnauthorizedException("UnauthorizedTest"));

            result.StatusCode.ShouldBe(( int )HttpStatusCode.Unauthorized);
            result.Body.Message.ShouldNotBeNullOrEmpty();
            result.Body.ErrorId.ShouldBeNullOrEmpty();
        }
        public void WhenHandlingForbiddenException_ReturnMesasageAndForbiddenStatusCode()
        {
            HttpExceptionHandler test   = GetHttpExceptionHandlerWithMockLoggerFactory();
            HttpExceptionResult  result = test.Handle(new ForbiddenException("ForbiddenTest"));

            result.StatusCode.ShouldBe(( int )HttpStatusCode.Forbidden);
            result.Body.Message.ShouldNotBeNullOrEmpty();
            result.Body.ErrorId.ShouldBeNullOrEmpty();
        }
Пример #9
0
        public static void Ignore_Is_Not_Set()
        {
            // Arrange
            var handler = new HttpExceptionHandler();

            // Act
            var result = handler.HandleException(new HttpException());

            // Assert
            Assert.False(result);
        }
Пример #10
0
        public static void Exception_Is_Null()
        {
            // Arrange
            var handler = new HttpExceptionHandler();

            // Act
            var result = handler.HandleException(null);

            // Assert
            Assert.False(result);
        }
Пример #11
0
        public static void NoMatch(Type type)
        {
            // Arrange
            var ex      = (Exception)Activator.CreateInstance(type);
            var handler = new HttpExceptionHandler();

            // Act
            var result = handler.HandleException(ex);

            // Assert
            Assert.False(result);
        }
Пример #12
0
        public static void Does_Not_Handle_Http_Code(int code)
        {
            // Arrange
            var handler = new HttpExceptionHandler();

            handler.Ignore = new[] { 400, 404 };

            // Act
            var result = handler.HandleException(new HttpException(code, "test"));

            // Assert
            Assert.False(result);
        }
Пример #13
0
        public Task Start(ServiceProvider serviceProvider)
        {
            IServiceScope scopeFactory()
            {
                return(serviceProvider.GetRequiredService <IServiceScopeFactory>().CreateScope());
            }

            var assembly = Assembly.GetExecutingAssembly();

            _server = new WebServer(o => o
                                    .WithUrlPrefix($"http://*:{_config.Port}")
                                    .WithMode(HttpListenerMode.EmbedIO))
                      .WithLocalSessionManager()
                      .WithModule(new WebSocketModuleChannel("/socket", serviceProvider))
                      .WithWebApi($"/service", m => m.WithController(() => new OpenApiController()))
                      .WithWebApi($"/api/{SerialHandler.PREFIX}", CustomResponseSerializer.None(false), m => m.WithController(() => new SerialApiController(scopeFactory())))
                      .WithWebApi($"/api/{JobService.PREFIX}", CustomResponseSerializer.None(false), m => m.WithController(() => new JobsApiController(scopeFactory())))
                      .WithWebApi($"/api/{FilesHandler.PREFIX}", CustomResponseSerializer.None(false), m => m.WithController(() => new FilesApiController(scopeFactory())))
                      .WithWebApi($"/api/{CommandHandler.PREFIX}", CustomResponseSerializer.None(false), m => m.WithController(() => new CommandApiController(scopeFactory())))
                      .WithEmbeddedResources("/", assembly, "GcodeController.web");
            var ipv4Address = Dns
                              .GetHostAddresses(Dns.GetHostName())
                              .Select(x => x.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork)
                              .FirstOrDefault();

            _logger.LogInformation($"Go to http://{ipv4Address}:{_config.Port}");
            _server.StateChanged += (s, e) => _logger.LogDebug($"WebServer New State - {e.NewState}");
            _server.HandleHttpException(async(context, exception) => {
                context.Response.StatusCode = exception.StatusCode;
                switch (exception.StatusCode)
                {
                case 404:
                    await context.SendStringAsync("Not Found", "plain/text", Encoding.UTF8);
                    break;

                default:
                    await HttpExceptionHandler.Default(context, exception);
                    break;
                }
            });
            return(_server.RunAsync(_cancellationToken));
        }
Пример #14
0
        private static void Main(string[] args)
        {
            var server = new WebServer("http://localhost:1234")
                         .WithModule(new MyModule("/custom"))
                         .WithLocalSessionManager(m =>
            {
                m.CookieDuration = TimeSpan.FromSeconds(5);
                //m.SessionDuration = TimeSpan.FromSeconds(5);
            })
                         .WithWebApi("/api", m =>
            {
                m.RegisterController <CustomController>();
                m.OnHttpException = HttpExceptionHandler.FullDataResponse(ResponseSerializer.Json);
            })
                         .WithStaticFolder("/", "../../../wwwroot", true)
                         .OnGet(async ctx => await ctx.SendDataAsync(new { Name = "Carlos", Last = "Solorzano", IsActibve = true }))
                         .OnPost(async ctx => await ctx.SendDataAsync(await ctx.GetRequestDataAsync <ContentJson>()));

            _ = server.RunAsync();

            Console.ReadLine();
        }
Пример #15
0
        private async Task <bool> HandlePlatibusRequest(IOwinContext context, IDiagnosticService diagnosticService)
        {
            if (!_resourceRouter.IsRoutable(context.Request.Uri))
            {
                return(false);
            }

            await diagnosticService.EmitAsync(
                new HttpEventBuilder(this, HttpEventType.HttpRequestReceived)
            {
                Remote = context.Request.RemoteIpAddress,
                Uri    = context.Request.Uri,
                Method = context.Request.Method
            }.Build());

            var resourceRequest  = new OwinRequestAdapter(context.Request);
            var resourceResponse = new OwinResponseAdapter(context.Response);

            try
            {
                await _resourceRouter.Route(resourceRequest, resourceResponse);
            }
            catch (Exception ex)
            {
                var exceptionHandler = new HttpExceptionHandler(resourceRequest, resourceResponse, diagnosticService);
                exceptionHandler.HandleException(ex);
            }

            await diagnosticService.EmitAsync(
                new HttpEventBuilder(this, HttpEventType.HttpResponseSent)
            {
                Remote = context.Request.RemoteIpAddress,
                Uri    = context.Request.Uri,
                Method = context.Request.Method,
                Status = context.Response.StatusCode
            }.Build());

            return(true);
        }
Пример #16
0
        private static void Main(string[] args)
        {
            var server = new WebServer("http://*****:*****@"C:\\Users\\ana.atayde\\source\\repos\\embedio-workshop\\wwwroot", true);

            //archivos staticos

            //server.OnPost(async ctx =>
            //{
            //    var request = await ctx.GetRequestDataAsync<ContentJson>();
            //    await ctx.SendDataAsync(request);
            //});
            server.RunAsync();

            Console.WriteLine("Hello World!");
            Console.ReadLine();
        }
 public void Initialise()
 {
     this.httpExceptionHandler   = new HttpExceptionHandler();
     this.operationRetrySettings = new OperationRetrySettings();
 }