当前位置: 首页>>代码示例>>C#>>正文


C# HttpServer.StartListening方法代码示例

本文整理汇总了C#中HttpServer.StartListening方法的典型用法代码示例。如果您正苦于以下问题:C# HttpServer.StartListening方法的具体用法?C# HttpServer.StartListening怎么用?C# HttpServer.StartListening使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在HttpServer的用法示例。


在下文中一共展示了HttpServer.StartListening方法的10个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。

示例1: TestAbortedEndReceive

        public void TestAbortedEndReceive()
        {
            var instance = new HttpServer(ProgramServersTests.Port)
            {
                Handler = new UrlResolver(
                    new UrlMapping(req => HttpResponse.PlainText("bunch of text"), path: "/static")
                ).Handle
            };
            try
            {
                instance.StartListening();

                TcpClient cl = new TcpClient();
                cl.Connect("localhost", ProgramServersTests.Port);
                cl.ReceiveTimeout = 1000; // 1 sec
                Socket sck = cl.Client;
                sck.Send("GET /static HTTP/1.1\r\nHost: localhost\r\n".ToUtf8());
                Thread.Sleep(500);
                instance.StopListening(true); // server must not throw after this; that’s the point of the test
                Assert.IsTrue(instance.ShutdownComplete.WaitOne(TimeSpan.FromSeconds(1))); // must shut down within at most 1 second
                sck.Close();
            }
            finally
            {
                instance.StopListening(brutal: true);
            }
        }
开发者ID:RT-Projects,项目名称:RT.Servers,代码行数:27,代码来源:ShutdownTests.cs

示例2: TestClientIPAddress

        public void TestClientIPAddress()
        {
            HttpRequest request = null;
            var instance = new HttpServer(ProgramServersTests.Port)
            {
                Handler = new UrlResolver(
                    new UrlMapping(req => { request = req; return HttpResponse.PlainText("blah"); }, path: "/static")
                ).Handle
            };
            try
            {
                instance.StartListening();

                TcpClient cl = new TcpClient();
                cl.Connect("localhost", ProgramServersTests.Port);
                cl.ReceiveTimeout = 1000; // 1 sec
                Socket sck = cl.Client;

                sck.Send("GET /static HTTP/1.1\r\nHost: localhost\r\nConnection: keep-alive\r\n\r\n".ToUtf8());
                TestUtil.ReadResponseUntilContent(sck);
                Assert.IsTrue(IPAddress.IsLoopback(request.ClientIPAddress));
                Assert.IsTrue(IPAddress.IsLoopback(request.SourceIP.Address));
                Assert.IsNull(request.Headers["X-Forwarded-For"]);

                sck.Send("GET /static HTTP/1.1\r\nHost: localhost\r\nConnection: keep-alive\r\nX-Forwarded-For: 12.34.56.78\r\n\r\n".ToUtf8());
                TestUtil.ReadResponseUntilContent(sck);
                Assert.AreEqual(IPAddress.Parse("12.34.56.78"), request.ClientIPAddress);
                Assert.IsTrue(IPAddress.IsLoopback(request.SourceIP.Address));
                Assert.IsNotNull(request.Headers["X-Forwarded-For"]);

                sck.Send("GET /static HTTP/1.1\r\nHost: localhost\r\nConnection: keep-alive\r\nX-Forwarded-For: 12.34.56.78:63125\r\n\r\n".ToUtf8());
                TestUtil.ReadResponseUntilContent(sck);
                Assert.AreEqual(IPAddress.Parse("12.34.56.78"), request.ClientIPAddress);
                Assert.IsTrue(IPAddress.IsLoopback(request.SourceIP.Address));
                Assert.IsNotNull(request.Headers["X-Forwarded-For"]);

                sck.Send("GET /static HTTP/1.1\r\nHost: localhost\r\nConnection: keep-alive\r\nX-Forwarded-For: 2a00:1450:400c:c01::93, 12.34.56.78\r\n\r\n".ToUtf8());
                TestUtil.ReadResponseUntilContent(sck);
                Assert.AreEqual(IPAddress.Parse("2a00:1450:400c:c01::93"), request.ClientIPAddress);
                Assert.AreEqual(IPAddress.Parse("2a00:1450:400c:c01::93"), request.Headers.XForwardedFor[0]);
                Assert.AreEqual(IPAddress.Parse("12.34.56.78"), request.Headers.XForwardedFor[1]);
                Assert.IsTrue(IPAddress.IsLoopback(request.SourceIP.Address));

                sck.Send("GET /static HTTP/1.1\r\nHost: localhost\r\nConnection: keep-alive\r\nX-Forwarded-For: [2a00:1450:400c:c01::93]:63125, 12.34.56.78:63125\r\n\r\n".ToUtf8());
                TestUtil.ReadResponseUntilContent(sck);
                Assert.AreEqual(IPAddress.Parse("2a00:1450:400c:c01::93"), request.ClientIPAddress);
                Assert.AreEqual(IPAddress.Parse("2a00:1450:400c:c01::93"), request.Headers.XForwardedFor[0]);
                Assert.AreEqual(IPAddress.Parse("12.34.56.78"), request.Headers.XForwardedFor[1]);
                Assert.IsTrue(IPAddress.IsLoopback(request.SourceIP.Address));

                sck.Close();
                instance.StopListening(true); // server must not throw after this; that’s the point of the test
            }
            finally
            {
                instance.StopListening(brutal: true);
            }
        }
开发者ID:RT-Projects,项目名称:RT.Servers,代码行数:58,代码来源:SpecialHeadersTests.cs

示例3: TestHalfOpenConnection

        public void TestHalfOpenConnection()
        {
            var instance = new HttpServer(ProgramServersTests.Port, new HttpServerOptions { OutputExceptionInformation = true });
            instance.Handler = req => HttpResponse.PlainText(" thingy stuff ");
            try
            {
                instance.StartListening();

                // A proper request ending in a half closed connection
                using (var cl = new TcpClient())
                {
                    cl.ReceiveTimeout = 1000; // 1 sec
                    cl.Connect("localhost", ProgramServersTests.Port);
                    cl.Client.Send("GET /static HTTP/1.1\r\nHost: localhost\r\nConnection: close\r\n\r\n".ToUtf8());
                    cl.Client.Shutdown(SocketShutdown.Send);
                    var response = Encoding.UTF8.GetString(cl.Client.ReceiveAllBytes());
                    var code = (HttpStatusCode) int.Parse(response.Substring("HTTP/1.1 ".Length, 3));
                    var parts = response.Split("\r\n\r\n");
                    Assert.AreEqual(HttpStatusCode._200_OK, code);
                    Assert.AreEqual(" thingy stuff ", parts[1]);
                }

                // An incomplete request ending in a half closed connection
                using (var cl = new TcpClient())
                {
                    cl.Connect("localhost", ProgramServersTests.Port);
                    cl.Client.Send("GET /static HTTP/1.1\r\nHost: localhost\r\nConnection: close".ToUtf8());
                    cl.Client.Shutdown(SocketShutdown.Send);
                    var response = Encoding.UTF8.GetString(cl.Client.ReceiveAllBytes());
                    // the test is that it doesn't wait forever
                }

                // A malformed request ending in a half closed connection
                using (var cl = new TcpClient())
                {
                    cl.Connect("localhost", ProgramServersTests.Port);
                    cl.Client.Send("xz".ToUtf8());
                    cl.Client.Shutdown(SocketShutdown.Send);
                    var response = Encoding.UTF8.GetString(cl.Client.ReceiveAllBytes());
                    // the test is that it doesn't wait forever
                }
            }
            finally
            {
                instance.StopListening(brutal: true);
            }
        }
开发者ID:RT-Projects,项目名称:RT.Servers,代码行数:47,代码来源:DisconnectionTests.cs

示例4: TestMidResponseSocketClosure

        public void TestMidResponseSocketClosure()
        {
            var instance = new HttpServer(ProgramServersTests.Port)
            {
                Handler = new UrlResolver(
                    new UrlMapping(req => { return HttpResponse.Create(enumInfinite(), "text/plain"); }, path: "/infinite-and-slow")
                ).Handle
            };
            try
            {
                instance.StartListening();

                ThreadStart thread = () =>
                {
                    for (int i = 0; i < 20; i++)
                    {
                        TcpClient cl = new TcpClient();
                        cl.Connect("localhost", ProgramServersTests.Port);
                        cl.ReceiveTimeout = 1000; // 1 sec
                        Socket sck = cl.Client;
                        sck.Send("GET /infinite-and-slow HTTP/1.1\r\nHost: localhost\r\nConnection: keep-alive\r\n\r\n".ToUtf8());
                        Thread.Sleep(100);
                        sck.Close();
                        GC.Collect();
                    }
                };
                var threads = Enumerable.Range(0, 10).Select(_ => new Thread(thread)).ToList();
                foreach (var t in threads)
                    t.Start();
                foreach (var t in threads)
                    t.Join();

                instance.StopListening(true); // server must not throw after this; that’s the point of the test
            }
            finally
            {
                instance.StopListening(brutal: true);
            }
        }
开发者ID:RT-Projects,项目名称:RT.Servers,代码行数:39,代码来源:DisconnectionTests.cs

示例5: TestKeepaliveShutdownGentle

        public void TestKeepaliveShutdownGentle()
        {
            var instance = new HttpServer(ProgramServersTests.Port)
            {
                Handler = new UrlResolver(
                    new UrlMapping(req => HttpResponse.PlainText("bunch of text"), path: "/static")
                ).Handle
            };
            try
            {
                instance.StartListening();

                TcpClient cl = new TcpClient();
                cl.Connect("localhost", ProgramServersTests.Port);
                cl.ReceiveTimeout = 1000; // 1 sec
                Socket sck = cl.Client;
                sck.Send("GET /static HTTP/1.1\r\nHost: localhost\r\n".ToUtf8());
                Thread.Sleep(500);
                Assert.AreEqual(1, instance.Stats.ActiveHandlers);
                sck.Send("Connection: keep-alive\r\n\r\n".ToUtf8());

                TestUtil.ReadResponseUntilContent(sck);
                Thread.Sleep(500);
                Assert.AreEqual(0, instance.Stats.ActiveHandlers);
                Assert.AreEqual(1, instance.Stats.KeepAliveHandlers);
                instance.StopListening();
                Assert.IsTrue(instance.ShutdownComplete.WaitOne(TimeSpan.FromSeconds(1))); // must shut down within at most 1 second
                Assert.AreEqual(0, instance.Stats.ActiveHandlers);
                Assert.AreEqual(0, instance.Stats.KeepAliveHandlers);
                sck.Close();
            }
            finally
            {
                instance.StopListening(brutal: true);
            }
        }
开发者ID:RT-Projects,项目名称:RT.Servers,代码行数:36,代码来源:ShutdownTests.cs

示例6: TestBasicRequestHandling

        public void TestBasicRequestHandling()
        {
            var store = 1024 * 1024;
            var instance = new HttpServer(ProgramServersTests.Port, new HttpServerOptions { StoreFileUploadInFileAtSize = store })
            {
                Handler = new UrlResolver(
                    new UrlMapping(handlerStatic, path: "/static"),
                    new UrlMapping(handlerDynamic, path: "/dynamic"),
                    new UrlMapping(handler64KFile, path: "/64kfile")
                ).Handle
            };
            try
            {
                instance.StartListening();

                testRequest("GET test #1", store, "GET / HTTP/1.1\r\nHost: localhost\r\n\r\n", (headers, content) =>
                {
                    Assert.AreEqual("HTTP/1.1 404 Not Found", headers[0]);
                    Assert.IsTrue(headers.Contains("Content-Type: text/html; charset=utf-8"));
                    Assert.IsTrue(headers.Any(x => x.StartsWith("Content-Length: ")));
                    Assert.IsTrue(content.FromUtf8().Contains("404"));
                });

                testRequest("GET test #2", store, "GET /static?x=y&z=%20&zig=%3D%3d HTTP/1.1\r\nHost: localhost\r\n\r\n", (headers, content) =>
                {
                    Assert.AreEqual("HTTP/1.1 200 OK", headers[0]);
                    Assert.IsTrue(headers.Contains("Content-Type: text/plain; charset=utf-8"));
                    Assert.IsTrue(headers.Contains("Content-Length: 41"));
                    Assert.AreEqual("GET:\nx => [\"y\"]\nz => [\" \"]\nzig => [\"==\"]\n", content.FromUtf8());
                });

                testRequest("GET test #3", store, "GET /static?x[]=1&x%5B%5D=%20&x%5b%5d=%3D%3d HTTP/1.1\r\nHost: localhost\r\n\r\n", (headers, content) =>
                {
                    Assert.AreEqual("HTTP/1.1 200 OK", headers[0]);
                    Assert.IsTrue(headers.Contains("Content-Type: text/plain; charset=utf-8"));
                    Assert.IsTrue(headers.Contains("Content-Length: 29"));
                    Assert.AreEqual("GET:\nx[] => [\"1\", \" \", \"==\"]\n", content.FromUtf8());
                });

                testRequest("GET test #4", store, "GET /dynamic?x=y&z=%20&zig=%3D%3d HTTP/1.1\r\nHost: localhost\r\n\r\n", (headers, content) =>
                {
                    Assert.AreEqual("HTTP/1.1 200 OK", headers[0]);
                    Assert.IsTrue(headers.Contains("Content-Type: text/plain; charset=utf-8"));
                    Assert.IsFalse(headers.Any(x => x.ToLowerInvariant().StartsWith("content-length:")));
                    Assert.IsFalse(headers.Any(x => x.ToLowerInvariant().StartsWith("accept-ranges:")));
                    Assert.AreEqual("GET:\nx => [\"y\"]\nz => [\" \"]\nzig => [\"==\"]\n", content.FromUtf8());
                });

                testRequest("GET test #5 (actually a POST)", store, "POST /static HTTP/1.1\r\nHost: localhost\r\n\r\n", (headers, content) =>
                {
                    Assert.AreEqual("HTTP/1.1 411 Length Required", headers[0]);
                    Assert.IsTrue(headers.Contains("Content-Type: text/html; charset=utf-8"));
                    Assert.IsTrue(headers.Contains("Connection: close"));
                    Assert.IsTrue(headers.Contains("Content-Length: " + content.Length));
                    Assert.IsTrue(content.FromUtf8().Contains("411"));
                });

                testRequest("GET test #6", store, "GET /64kfile HTTP/1.1\r\nHost: localhost\r\n\r\n", (headers, content) =>
                {
                    Assert.AreEqual("HTTP/1.1 200 OK", headers[0]);
                    Assert.IsTrue(headers.Contains("Content-Type: application/octet-stream"));
                    Assert.IsTrue(headers.Contains("Content-Length: 65536"));
                    Assert.IsTrue(headers.Contains("Accept-Ranges: bytes"));
                    Assert.AreEqual(65536, content.Length);
                    for (int i = 0; i < content.Length; i++)
                        Assert.AreEqual(content[i], (byte) (i % 256));
                });

                testRequest("GET test #7", store, "GET /64kfile HTTP/1.1\r\nHost: localhost\r\nRange: bytes=23459-38274\r\n\r\n", (headers, content) =>
                {
                    Assert.AreEqual("HTTP/1.1 206 Partial Content", headers[0]);
                    Assert.IsTrue(headers.Contains("Accept-Ranges: bytes"));
                    Assert.IsTrue(headers.Contains("Content-Range: bytes 23459-38274/65536"));
                    Assert.IsTrue(headers.Contains("Content-Type: application/octet-stream"));
                    Assert.IsTrue(headers.Contains("Content-Length: 14816"));
                    for (int i = 0; i < content.Length; i++)
                        Assert.AreEqual((byte) ((163 + i) % 256), content[i]);
                });

                testRequest("GET test #8", store, "GET /64kfile HTTP/1.1\r\nHost: localhost\r\nRange: bytes=65-65,67-67\r\n\r\n", (headers, content) =>
                {
                    Assert.AreEqual("HTTP/1.1 206 Partial Content", headers[0]);
                    Assert.IsTrue(headers.Contains("Accept-Ranges: bytes"));
                    Assert.IsTrue(headers.Any(x => Regex.IsMatch(x, @"^Content-Type: multipart/byteranges; boundary=[0-9A-F]+$")));
                    string boundary = headers.First(x => Regex.IsMatch(x, @"^Content-Type: multipart/byteranges; boundary=[0-9A-F]+$")).Substring(45);
                    Assert.IsTrue(headers.Contains("Content-Length: 284"));
                    byte[] expectedContent = ("--" + boundary + "\r\nContent-Range: bytes 65-65/65536\r\n\r\nA\r\n--" + boundary + "\r\nContent-Range: bytes 67-67/65536\r\n\r\nC\r\n--" + boundary + "--\r\n").ToUtf8();
                    Assert.AreEqual(expectedContent.Length, content.Length);
                    for (int i = 0; i < expectedContent.Length; i++)
                        Assert.AreEqual(expectedContent[i], content[i]);
                });

                testRequest("GET test #9", store, "GET /64kfile HTTP/1.1\r\nHost: localhost\r\nAccept-Encoding: gzip\r\n\r\n", (headers, content) =>
                {
                    Assert.AreEqual("HTTP/1.1 200 OK", headers[0]);
                    Assert.IsTrue(headers.Contains("Accept-Ranges: bytes"));
                    Assert.IsTrue(headers.Contains("Content-Type: application/octet-stream"));
                    Assert.IsTrue(headers.Contains("Content-Encoding: gzip"));
                    Assert.IsTrue(headers.Any(h => h.StartsWith("Content-Length")));
                    GZipStream gz = new GZipStream(new MemoryStream(content), CompressionMode.Decompress);
//.........这里部分代码省略.........
开发者ID:RT-Projects,项目名称:RT.Servers,代码行数:101,代码来源:RequestResponseTests.cs

示例7: TestKeepaliveAndChunked

        public void TestKeepaliveAndChunked()
        {
            HttpServer instance = new HttpServer(ProgramServersTests.Port) { Handler = handlerDynamic };
            try
            {
                instance.StartListening();
                Thread.Sleep(100);
                Assert.AreEqual(0, instance.Stats.ActiveHandlers);
                Assert.AreEqual(0, instance.Stats.KeepAliveHandlers);

                TcpClient cl = new TcpClient();
                cl.Connect("localhost", ProgramServersTests.Port);
                cl.ReceiveTimeout = 1000; // 1 sec
                Socket sck = cl.Client;

                // Run three consecutive requests within the same connection using Connection: Keep-alive
                keepaliveAndChunkedPrivate(sck);
                Thread.Sleep(300);
                Assert.AreEqual(0, instance.Stats.ActiveHandlers);
                Assert.AreEqual(1, instance.Stats.KeepAliveHandlers);
                keepaliveAndChunkedPrivate(sck);
                Thread.Sleep(300);
                Assert.AreEqual(0, instance.Stats.ActiveHandlers);
                Assert.AreEqual(1, instance.Stats.KeepAliveHandlers);
                keepaliveAndChunkedPrivate(sck);
                Thread.Sleep(300);
                Assert.AreEqual(0, instance.Stats.ActiveHandlers);
                Assert.AreEqual(1, instance.Stats.KeepAliveHandlers);

                instance.StopListening();
                Assert.IsTrue(instance.ShutdownComplete.WaitOne(TimeSpan.FromSeconds(1)));
                Assert.AreEqual(0, instance.Stats.ActiveHandlers);
                Assert.AreEqual(0, instance.Stats.KeepAliveHandlers);

                sck.Close();
                cl.Close();
            }
            finally
            {
                instance.StopListening(true);
            }
        }
开发者ID:RT-Projects,项目名称:RT.Servers,代码行数:42,代码来源:RequestResponseTests.cs

示例8: TestDomainCase

        public void TestDomainCase()
        {
            var instance = new HttpServer(ProgramServersTests.Port, new HttpServerOptions { OutputExceptionInformation = true });
            try
            {
                bool ok;
                instance.Handler = new UrlResolver(
                    new UrlMapping(domain: "example.com", handler: req => { ok = true; return HttpResponse.Empty(); })
                ).Handle;

                var getResponse = Ut.Lambda((string host) =>
                {
                    TcpClient cl = new TcpClient();
                    cl.Connect("localhost", ProgramServersTests.Port);
                    cl.ReceiveTimeout = 1000; // 1 sec
                    cl.Client.Send(("GET /static HTTP/1.1\r\nHost: " + host + "\r\nConnection: close\r\n\r\n").ToUtf8());
                    var response = Encoding.UTF8.GetString(cl.Client.ReceiveAllBytes());
                    cl.Close();
                    var code = (HttpStatusCode) int.Parse(response.Substring("HTTP/1.1 ".Length, 3));
                    var parts = response.Split("\r\n\r\n");
                    return Tuple.Create(code, parts[1]);
                });

                instance.StartListening();

                ok = false;
                getResponse("blah.com");
                Assert.IsFalse(ok);

                ok = false;
                getResponse("www.example.com");
                Assert.IsTrue(ok);

                ok = false;
                getResponse("WWW.EXAMPLE.COM");
                Assert.IsTrue(ok);

                ok = false;
                getResponse("www.exAmple.com");
                Assert.IsTrue(ok);
            }
            finally
            {
                instance.StopListening(brutal: true);
            }
        }
开发者ID:RT-Projects,项目名称:RT.Servers,代码行数:46,代码来源:UrlPathResolverTests.cs

示例9: TestErrorHandlerExceptions

        public void TestErrorHandlerExceptions()
        {
            var instance = new HttpServer(ProgramServersTests.Port, new HttpServerOptions { OutputExceptionInformation = true });
            try
            {
                instance.StartListening();

                var getResponse = Ut.Lambda(() =>
                {
                    TcpClient cl = new TcpClient();
                    cl.Connect("localhost", ProgramServersTests.Port);
                    cl.ReceiveTimeout = 1000; // 1 sec
                    cl.Client.Send("GET /static HTTP/1.1\r\nHost: localhost\r\nConnection: close\r\n\r\n".ToUtf8());
                    var response = Encoding.UTF8.GetString(cl.Client.ReceiveAllBytes());
                    cl.Close();
                    var code = (HttpStatusCode) int.Parse(response.Substring("HTTP/1.1 ".Length, 3));
                    var parts = response.Split("\r\n\r\n");
                    return Tuple.Create(code, parts[1]);
                });

                // Test that we get a 404 response with no handlers
                var resp = getResponse();
                Assert.AreEqual(HttpStatusCode._404_NotFound, resp.Item1);

                // Test that having only an error handler works as expected
                instance.ErrorHandler = (req, err) => { return HttpResponse.Create("blah", "text/plain", HttpStatusCode._407_ProxyAuthenticationRequired); };
                resp = getResponse();
                Assert.AreEqual(HttpStatusCode._407_ProxyAuthenticationRequired, resp.Item1);
                Assert.AreEqual("blah", resp.Item2);

                // Test that having no error handler uses the default one
                instance.ErrorHandler = null;
                instance.Handler = req => { throw new HttpException(HttpStatusCode._305_UseProxy); };
                resp = getResponse();
                Assert.AreEqual(HttpStatusCode._305_UseProxy, resp.Item1);

                // Test that the exception and request are passed on to the error handler
                HttpRequest storedReq = null;
                Exception storedEx = null;
                bool ok = false;
                instance.Handler = req => { storedEx = new HttpException(HttpStatusCode._402_PaymentRequired); storedReq = req; throw storedEx; };
                instance.ErrorHandler = (req, ex) => { ok = object.ReferenceEquals(req, storedReq) && object.ReferenceEquals(ex, storedEx); return HttpResponse.Create("blah", "text/plain"); };
                resp = getResponse();
                Assert.IsTrue(ok);

                // Test that exception in error handler invokes the default one, and uses the *original* status code
                instance.Handler = req => { throw new HttpException(HttpStatusCode._201_Created); };
                instance.ErrorHandler = (req, ex) => { throw new HttpException(HttpStatusCode._403_Forbidden); };
                resp = getResponse();
                Assert.AreEqual(HttpStatusCode._201_Created, resp.Item1);

                // Test that a non-HttpException is properly handled
                ok = false;
                instance.Handler = req => { throw storedEx = new Exception("Blah!"); };
                instance.ErrorHandler = (req, ex) => { ok = object.ReferenceEquals(ex, storedEx); return HttpResponse.Create("blah", "text/plain"); };
                resp = getResponse();
                Assert.IsTrue(ok);
                Assert.AreEqual(HttpStatusCode._200_OK, resp.Item1);
                Assert.AreEqual("blah", resp.Item2);
                instance.ErrorHandler = null;
                resp = getResponse();
                Assert.AreEqual(HttpStatusCode._500_InternalServerError, resp.Item1);

                // Test that the main handler returning null results in a 500 error (via InvalidOperationException)
                instance.Handler = req => { return null; };
                instance.ErrorHandler = (req, ex) => { storedEx = ex; throw new HttpException(HttpStatusCode._203_NonAuthoritativeInformation); };
                resp = getResponse();
                Assert.IsTrue(storedEx is InvalidOperationException);
                Assert.AreEqual(HttpStatusCode._500_InternalServerError, resp.Item1);

                // Test that the error handler returning null invokes the default error handler
                instance.Handler = req => { throw new HttpException(HttpStatusCode._201_Created); };
                instance.ErrorHandler = (req, ex) => { return null; };
                resp = getResponse();
                Assert.AreEqual(HttpStatusCode._201_Created, resp.Item1);

                // Test that a malformed request passes through the error handler
                instance.ErrorHandler = (req, ex) => { storedEx = ex; throw new HttpException(HttpStatusCode._204_NoContent); };
                {
                    TcpClient cl = new TcpClient();
                    cl.Connect("localhost", ProgramServersTests.Port);
                    cl.ReceiveTimeout = 1000; // 1 sec
                    cl.Client.Send("xz\r\n\r\n".ToUtf8());
                    var response = Encoding.UTF8.GetString(cl.Client.ReceiveAllBytes());
                    cl.Close();
                    var code = (HttpStatusCode) int.Parse(response.Substring("HTTP/1.1 ".Length, 3));
                    var body = response.Split("\r\n\r\n")[1];
                    Assert.AreEqual(HttpStatusCode._400_BadRequest, code);
                    Assert.IsTrue(storedEx is HttpRequestParseException);
                    Assert.AreEqual(HttpStatusCode._400_BadRequest, (storedEx as HttpRequestParseException).StatusCode);
                }

                // Test that an exception in the response stream is sent to the response exception handler
                var excp = new Exception("Blam!");
                HttpResponse storedRsp1 = null, storedRsp2 = null;
                instance.Handler = req => { return storedRsp1 = HttpResponse.Create(new DynamicContentStream(enumerableWithException(excp)), "text/plain"); };
                bool ok1 = true, ok2 = false;
                instance.ErrorHandler = (req, ex) => { ok1 = false; return null; };
                instance.ResponseExceptionHandler = (req, ex, rsp) => { ok2 = true; storedEx = ex; storedRsp2 = rsp; };
                resp = getResponse();
//.........这里部分代码省略.........
开发者ID:RT-Projects,项目名称:RT.Servers,代码行数:101,代码来源:ErrorHandlerTests.cs

示例10: TestErrorHandlerAndCleanUp

        public void TestErrorHandlerAndCleanUp()
        {
            var instance = new HttpServer(ProgramServersTests.Port);
            try
            {
                bool errorHandlerCalled = false;
                bool cleanUpCalled = false;

                instance.StartListening();
                instance.Handler = req =>
                {
                    req.CleanUpCallback = () =>
                    {
                        Assert.IsTrue(errorHandlerCalled);
                        cleanUpCalled = true;
                    };
                    throw new InvalidOperationException();
                };
                instance.ErrorHandler = (req, exc) =>
                {
                    Assert.IsFalse(cleanUpCalled);
                    errorHandlerCalled = true;
                    return HttpResponse.PlainText("Error");
                };

                TcpClient cl = new TcpClient();
                cl.Connect("localhost", ProgramServersTests.Port);
                cl.ReceiveTimeout = 1000000; // 1000 sec
                cl.Client.Send("GET / HTTP/1.1\r\nHost: localhost\r\n\r\n".ToUtf8());
                var response = Encoding.UTF8.GetString(cl.Client.ReceiveAllBytes());
                cl.Close();
                Assert.IsTrue(errorHandlerCalled);
                Assert.IsTrue(cleanUpCalled);
                Assert.IsTrue(response.EndsWith("\r\n\r\nError"));
            }
            finally
            {
                instance.StopListening(brutal: true);
            }
        }
开发者ID:RT-Projects,项目名称:RT.Servers,代码行数:40,代码来源:ErrorHandlerTests.cs


注:本文中的HttpServer.StartListening方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。