コード例 #1
0
        public void Invoke_SetsResponseBody()
        {
            var response     = new HttpResponseMessage(HttpStatusCode.OK);
            var expectedBody = @"{""x"":""y""}";

            response.Content = new StringContent(expectedBody, Encoding.UTF8, "application/json");
            var handler = new HandlerStub()
            {
                Response = response
            };
            var bufferPolicySelector = CreateBufferPolicySelector(bufferInput: false, bufferOutput: false);
            var environment          = CreateOwinEnvironment("GET", "http", "localhost", "/vroot", "/api/customers");
            var responseStream       = new MemoryStream();

            environment["owin.ResponseBody"] = responseStream;
            var adapter = new HttpMessageHandlerAdapter(next: null, messageHandler: handler, bufferPolicySelector: bufferPolicySelector);

            adapter.Invoke(new OwinContext(environment)).Wait();

            responseStream.Seek(0, SeekOrigin.Begin);
            byte[] bodyBytes = new byte[9];
            int    charsRead = responseStream.Read(bodyBytes, 0, 9);

            // Assert that we can read 9 characters and no more characters after that
            Assert.Equal(9, charsRead);
            Assert.Equal(-1, responseStream.ReadByte());
            Assert.Equal(expectedBody, Encoding.UTF8.GetString(bodyBytes));
        }
コード例 #2
0
        public void Invoke_RespectsInputBufferingSetting(bool bufferInput)
        {
            var handler = CreateOKHandlerStub();
            var bufferPolicySelector = CreateBufferPolicySelector(bufferInput: bufferInput, bufferOutput: false);
            var environment          = CreateOwinEnvironment("GET", "http", "localhost", "/vroot", "/api/customers");
            var expectedBody         = "This is the request body.";
            var requestBodyMock      = new Mock <MemoryStream>(Encoding.UTF8.GetBytes(expectedBody));

            requestBodyMock.CallBase = true;
            requestBodyMock.Setup(s => s.CanSeek).Returns(false);
            MemoryStream requestBody = requestBodyMock.Object;

            environment["owin.RequestBody"] = requestBody;
            var adapter = new HttpMessageHandlerAdapter(next: null, messageHandler: handler, bufferPolicySelector: bufferPolicySelector);

            adapter.Invoke(new OwinContext(environment)).Wait();

            if (bufferInput)
            {
                Assert.False(requestBody.CanRead);
                // Assert that the OWIN environment still has a request body that can be read
                var    owinRequestBody = environment["owin.RequestBody"] as Stream;
                byte[] bodyBytes       = new byte[25];
                int    charsRead       = owinRequestBody.Read(bodyBytes, 0, 25);
                Assert.Equal(expectedBody, Encoding.UTF8.GetString(bodyBytes));
            }
            else
            {
                Assert.True(requestBody.CanRead);
            }
            // Assert that Web API gets the right body
            var request = handler.Request;

            Assert.Equal(expectedBody, request.Content.ReadAsStringAsync().Result);
        }
コード例 #3
0
        public void Invoke_RespectsOutputBufferingSetting(bool bufferOutput)
        {
            var response = new HttpResponseMessage(HttpStatusCode.OK);

            response.Content = new ObjectContent <string>("blue", new JsonMediaTypeFormatter());
            var handler = new HandlerStub()
            {
                Response = response
            };
            var bufferPolicySelector = CreateBufferPolicySelector(bufferInput: false, bufferOutput: bufferOutput);
            var environment          = CreateOwinEnvironment("GET", "http", "localhost", "/vroot", "/api/customers");
            var adapter = new HttpMessageHandlerAdapter(next: null, messageHandler: handler, bufferPolicySelector: bufferPolicySelector);

            adapter.Invoke(new OwinContext(environment)).Wait();

            var responseHeaders = environment["owin.ResponseHeaders"] as IDictionary <string, string[]>;

            if (bufferOutput)
            {
                Assert.True(responseHeaders.ContainsKey("Content-Length"));
            }
            else
            {
                Assert.False(responseHeaders.ContainsKey("Content-Length"));
            }
        }
コード例 #4
0
        public void Invoke_ThrowsOnNullResponse()
        {
            var handler = CreateOKHandlerStub();
            var bufferPolicySelector = CreateBufferPolicySelector(bufferInput: false, bufferOutput: false);
            var adapter = new HttpMessageHandlerAdapter(next: null, messageHandler: handler, bufferPolicySelector: bufferPolicySelector);
            var mockContext = new Mock<IOwinContext>();
            mockContext.Setup(context => context.Request).Returns(new OwinRequest());

            Assert.Throws<InvalidOperationException>(
                () => adapter.Invoke(mockContext.Object).Wait(),
                "The OWIN context's Response property must not be null.");
        }
コード例 #5
0
        public void Invoke_BuildsAppropriateRequestMessage()
        {
            var handler = CreateOKHandlerStub();
            var bufferPolicySelector = CreateBufferPolicySelector(bufferInput: false, bufferOutput: false);
            var environment = CreateOwinEnvironment("GET", "http", "localhost", "/vroot", "/api/customers");
            var adapter = new HttpMessageHandlerAdapter(next: null, messageHandler: handler, bufferPolicySelector: bufferPolicySelector);

            adapter.Invoke(new OwinContext(environment)).Wait();

            var request = handler.Request;
            Assert.Equal(HttpMethod.Get, request.Method);
            Assert.Equal("http://localhost/vroot/api/customers", request.RequestUri.AbsoluteUri);
        }
        public void Invoke_BuildsUriWithHostAndPort()
        {
            var handler = CreateOKHandlerStub();
            var bufferPolicySelector = CreateBufferPolicySelector(bufferInput: false, bufferOutput: false);
            var environment = CreateEnvironment("GET", "http", "localhost:12345", "/vroot", "/api/customers");
            var adapter = new HttpMessageHandlerAdapter(env => TaskHelpers.Completed(), handler, bufferPolicySelector);

            adapter.Invoke(environment).Wait();

            var request = handler.Request;
            Assert.Equal(HttpMethod.Get, request.Method);
            Assert.Equal("http://localhost:12345/vroot/api/customers", request.RequestUri.AbsoluteUri);
        }
コード例 #7
0
        public void Invoke_SetsOwinEnvironment()
        {
            var handler = CreateOKHandlerStub();
            var bufferPolicySelector = CreateBufferPolicySelector(bufferInput: false, bufferOutput: false);
            var environment          = CreateOwinEnvironment("GET", "http", "localhost", "/vroot", "/api/customers");
            var adapter = new HttpMessageHandlerAdapter(next: null, messageHandler: handler, bufferPolicySelector: bufferPolicySelector);

            adapter.Invoke(new OwinContext(environment)).Wait();

            var request = handler.Request;

            Assert.Same(environment, request.GetOwinEnvironment());
        }
        public void Invoke_Throws_IfHostHeaderMissing()
        {
            var handler = CreateOKHandlerStub();
            var bufferPolicySelector = CreateBufferPolicySelector(bufferInput: false, bufferOutput: false);
            var environment = CreateEnvironment("GET", "http", "localhost", "/vroot", "/api/customers");
            var requestHeaders = environment["owin.RequestHeaders"] as IDictionary<string, string[]>;
            requestHeaders.Remove("Host");
            var adapter = new HttpMessageHandlerAdapter(env => TaskHelpers.Completed(), handler, bufferPolicySelector);

            Assert.Throws<InvalidOperationException>(
                () => adapter.Invoke(environment).Wait(),
                "The OWIN environment does not contain a value for the required 'Host' header.");
        }
コード例 #9
0
        public void Invoke_ThrowsOnNullResponse()
        {
            var handler = CreateOKHandlerStub();
            var bufferPolicySelector = CreateBufferPolicySelector(bufferInput: false, bufferOutput: false);
            var adapter     = new HttpMessageHandlerAdapter(next: null, messageHandler: handler, bufferPolicySelector: bufferPolicySelector);
            var mockContext = new Mock <IOwinContext>();

            mockContext.Setup(context => context.Request).Returns(new OwinRequest());

            Assert.Throws <InvalidOperationException>(
                () => adapter.Invoke(mockContext.Object).Wait(),
                "The OWIN context's Response property must not be null.");
        }
コード例 #10
0
        public void Invoke_CallsMessageHandler_WithEnvironmentCancellationToken()
        {
            var handler = CreateOKHandlerStub();
            var bufferPolicySelector = CreateBufferPolicySelector(bufferInput: false, bufferOutput: false);
            var environment          = CreateOwinEnvironment("GET", "http", "localhost", "/vroot", "/api/customers");
            var cancellationToken    = new CancellationToken();

            environment["owin.CallCancelled"] = cancellationToken;
            var adapter = new HttpMessageHandlerAdapter(next: null, messageHandler: handler, bufferPolicySelector: bufferPolicySelector);

            adapter.Invoke(new OwinContext(environment)).Wait();

            Assert.Equal(cancellationToken, handler.CancellationToken);
        }
コード例 #11
0
        public void Invoke_CreatesUri_ThatGeneratesCorrectlyDecodedStrings(string decodedId)
        {
            var handler = CreateOKHandlerStub();
            var bufferPolicySelector = CreateBufferPolicySelector(bufferInput: false, bufferOutput: false);
            var environment          = CreateOwinEnvironment("GET", "http", "localhost", "/vroot", "/api/customers/" + decodedId);
            var adapter = new HttpMessageHandlerAdapter(next: null, messageHandler: handler, bufferPolicySelector: bufferPolicySelector);
            var route   = new HttpRoute("api/customers/{id}");

            adapter.Invoke(new OwinContext(environment)).Wait();
            IHttpRouteData routeData = route.GetRouteData("/vroot", handler.Request);

            Assert.NotNull(routeData);
            Assert.Equal(decodedId, routeData.Values["id"]);
        }
コード例 #12
0
        public void Invoke_BuildsUriWithHostAndPort()
        {
            var handler = CreateOKHandlerStub();
            var bufferPolicySelector = CreateBufferPolicySelector(bufferInput: false, bufferOutput: false);
            var environment          = CreateOwinEnvironment("GET", "http", "localhost:12345", "/vroot", "/api/customers");
            var adapter = new HttpMessageHandlerAdapter(next: null, messageHandler: handler, bufferPolicySelector: bufferPolicySelector);

            adapter.Invoke(new OwinContext(environment)).Wait();

            var request = handler.Request;

            Assert.Equal(HttpMethod.Get, request.Method);
            Assert.Equal("http://localhost:12345/vroot/api/customers", request.RequestUri.AbsoluteUri);
        }
コード例 #13
0
        public void Invoke_CallsMessageHandler_WithEnvironmentUser()
        {
            var handler = CreateOKHandlerStub();
            var bufferPolicySelector = CreateBufferPolicySelector(bufferInput: false, bufferOutput: false);
            var environment          = CreateOwinEnvironment("GET", "http", "localhost", "/vroot", "/api/customers");
            var user = new Mock <IPrincipal>().Object;

            environment["server.User"] = user;
            var adapter = new HttpMessageHandlerAdapter(next: null, messageHandler: handler, bufferPolicySelector: bufferPolicySelector);

            adapter.Invoke(new OwinContext(environment)).Wait();

            Assert.Equal(user, handler.User);
        }
コード例 #14
0
        public void Invoke_DoesNotCallNext_IfMessageHandlerDoesNotAddNoRouteMatchedProperty()
        {
            var mockNext = new Mock <OwinMiddleware>(MockBehavior.Strict, null);
            HttpResponseMessage response = new HttpResponseMessage(HttpStatusCode.NotFound);
            var handler = new HandlerStub()
            {
                Response = response, AddNoRouteMatchedKey = false
            };
            var bufferPolicySelector = CreateBufferPolicySelector(bufferInput: false, bufferOutput: false);
            var environment          = CreateOwinEnvironment("GET", "http", "localhost", "/vroot", "/api/customers");
            var adapter = new HttpMessageHandlerAdapter(next: mockNext.Object, messageHandler: handler, bufferPolicySelector: bufferPolicySelector);

            Assert.DoesNotThrow(
                () => adapter.Invoke(new OwinContext(environment)).Wait());
        }
コード例 #15
0
        public void Invoke_Throws_IfMessageHandlerReturnsNull()
        {
            HttpResponseMessage response = null;
            var handler = new HandlerStub()
            {
                Response = response
            };
            var bufferPolicySelector = CreateBufferPolicySelector(bufferInput: false, bufferOutput: false);
            var environment          = CreateOwinEnvironment("GET", "http", "localhost", "/vroot", "/api/customers");
            var adapter = new HttpMessageHandlerAdapter(next: null, messageHandler: handler, bufferPolicySelector: bufferPolicySelector);

            Assert.Throws <InvalidOperationException>(
                () => adapter.Invoke(new OwinContext(environment)).Wait(),
                "The message handler did not return a response message.");
        }
コード例 #16
0
        public void Invoke_SetsRequestBodyOnRequestMessage()
        {
            var handler = CreateOKHandlerStub();
            var bufferPolicySelector = CreateBufferPolicySelector(bufferInput: false, bufferOutput: false);
            var environment          = CreateOwinEnvironment("GET", "http", "localhost", "/vroot", "/api/customers");
            var expectedBody         = "This is the request body.";

            environment["owin.RequestBody"] = new MemoryStream(Encoding.UTF8.GetBytes(expectedBody));
            var adapter = new HttpMessageHandlerAdapter(next: null, messageHandler: handler, bufferPolicySelector: bufferPolicySelector);

            adapter.Invoke(new OwinContext(environment)).Wait();

            var request = handler.Request;

            Assert.Equal(expectedBody, request.Content.ReadAsStringAsync().Result);
        }
コード例 #17
0
        public void Invoke_SetsClientCertificate()
        {
            var handler = CreateOKHandlerStub();
            var bufferPolicySelector = CreateBufferPolicySelector(bufferInput: false, bufferOutput: false);
            var environment          = CreateOwinEnvironment("GET", "http", "localhost", "/vroot", "/api/customers");
            var clientCert           = new Mock <X509Certificate2>().Object;

            environment["ssl.ClientCertificate"] = clientCert;
            var adapter = new HttpMessageHandlerAdapter(next: null, messageHandler: handler, bufferPolicySelector: bufferPolicySelector);

            adapter.Invoke(new OwinContext(environment)).Wait();

            var request = handler.Request;

            Assert.Equal(clientCert, request.GetClientCertificate());
        }
コード例 #18
0
        public void Invoke_AddsZeroContentLengthHeader_WhenThereIsNoContent()
        {
            var response = new HttpResponseMessage(HttpStatusCode.OK);
            var handler  = new HandlerStub()
            {
                Response = response
            };
            var bufferPolicySelector = CreateBufferPolicySelector(bufferInput: false, bufferOutput: false);
            var environment          = CreateOwinEnvironment("GET", "http", "localhost", "/vroot", "/api/customers");
            var adapter = new HttpMessageHandlerAdapter(next: null, messageHandler: handler, bufferPolicySelector: bufferPolicySelector);

            adapter.Invoke(new OwinContext(environment)).Wait();

            var responseHeaders = environment["owin.ResponseHeaders"] as IDictionary <string, string[]>;

            Assert.Equal("0", responseHeaders["Content-Length"][0]);
        }
コード例 #19
0
        public void Invoke_CallsNext_IfMessageHandlerReturns404WithNoRouteMatched()
        {
            var nextMock = new Mock <OwinMiddleware>(null);

            nextMock.Setup(middleware => middleware.Invoke(It.IsAny <OwinContext>())).Returns(TaskHelpers.Completed()).Verifiable();
            HttpResponseMessage response = new HttpResponseMessage(HttpStatusCode.NotFound);
            var handler = new HandlerStub()
            {
                Response = response, AddNoRouteMatchedKey = true
            };
            var bufferPolicySelector = CreateBufferPolicySelector(bufferInput: false, bufferOutput: false);
            var environment          = CreateOwinEnvironment("GET", "http", "localhost", "/vroot", "/api/customers");
            var adapter = new HttpMessageHandlerAdapter(next: nextMock.Object, messageHandler: handler, bufferPolicySelector: bufferPolicySelector);

            adapter.Invoke(new OwinContext(environment)).Wait();

            nextMock.Verify();
        }
コード例 #20
0
        public void Invoke_SetsRequestIsLocalProperty(bool?isLocal, bool expectedRequestLocal)
        {
            var handler = CreateOKHandlerStub();
            var bufferPolicySelector = CreateBufferPolicySelector(bufferInput: false, bufferOutput: false);
            var environment          = CreateOwinEnvironment("GET", "http", "localhost", "/vroot", "/api/customers");

            if (isLocal.HasValue)
            {
                environment["server.IsLocal"] = isLocal.Value;
            }
            var adapter = new HttpMessageHandlerAdapter(next: null, messageHandler: handler, bufferPolicySelector: bufferPolicySelector);

            adapter.Invoke(new OwinContext(environment)).Wait();

            var request = handler.Request;

            Assert.Equal(expectedRequestLocal, request.IsLocal());
        }
コード例 #21
0
ファイル: Program.cs プロジェクト: mehuledu/ndc
 public static Func<IDictionary<string, object>, Task> CreateWebApiAppFunc2(HttpConfiguration config, HttpMessageHandlerOptions options = null)
 {
     var bufferPolicy = new OwinBufferPolicySelector();
     config.Services.Replace(typeof(IHostBufferPolicySelector), bufferPolicy); // Done just so App can get access to it.   
     var app = new HttpServer(config);
     if (options == null)
     {
         options = new HttpMessageHandlerOptions()
         {
             MessageHandler = app,
             BufferPolicySelector = bufferPolicy,
             ExceptionLogger = new GlobalErrorLoggingService(),
             ExceptionHandler = new GlobalErrorHandlerService()
         };
     }
     var handler = new HttpMessageHandlerAdapter(new NotFoundMiddleware(), options);
     return (env) => handler.Invoke(new OwinContext(env));
 }
コード例 #22
0
        public void Invoke_SetsResponseStatusCodeAndReasonPhrase()
        {
            var expectedReasonPhrase = "OH NO!";
            var response             = new HttpResponseMessage(HttpStatusCode.ServiceUnavailable)
            {
                ReasonPhrase = expectedReasonPhrase
            };
            var handler = new HandlerStub()
            {
                Response = response
            };
            var bufferPolicySelector = CreateBufferPolicySelector(bufferInput: false, bufferOutput: false);
            var environment          = CreateOwinEnvironment("GET", "http", "localhost", "/vroot", "/api/customers");
            var adapter = new HttpMessageHandlerAdapter(next: null, messageHandler: handler, bufferPolicySelector: bufferPolicySelector);

            adapter.Invoke(new OwinContext(environment)).Wait();

            Assert.Equal(503, environment["owin.ResponseStatusCode"]);
            Assert.Equal(expectedReasonPhrase, environment["owin.ResponseReasonPhrase"]);
        }
コード例 #23
0
        public void Invoke_AddsTransferEncodingChunkedHeaderIfThereIsNoContentLength()
        {
            var response = new HttpResponseMessage(HttpStatusCode.OK);

            response.Content = new ObjectContent <string>("blue", new JsonMediaTypeFormatter());
            var handler = new HandlerStub()
            {
                Response = response
            };
            var bufferPolicySelector = CreateBufferPolicySelector(bufferInput: false, bufferOutput: false);
            var environment          = CreateOwinEnvironment("GET", "http", "localhost", "/vroot", "/api/customers");
            var adapter = new HttpMessageHandlerAdapter(next: null, messageHandler: handler, bufferPolicySelector: bufferPolicySelector);

            adapter.Invoke(new OwinContext(environment)).Wait();

            var responseHeaders = environment["owin.ResponseHeaders"] as IDictionary <string, string[]>;

            Assert.Equal("chunked", responseHeaders["Transfer-Encoding"][0]);
            Assert.False(responseHeaders.ContainsKey("Content-Length"));
        }
コード例 #24
0
        public void Invoke_AddsRequestHeadersToRequestMessage()
        {
            var handler = CreateOKHandlerStub();
            var bufferPolicySelector = CreateBufferPolicySelector(bufferInput: false, bufferOutput: false);
            var environment          = CreateOwinEnvironment("GET", "http", "localhost", "/vroot", "/api/customers");
            var requestHeaders       = environment["owin.RequestHeaders"] as IDictionary <string, string[]>;

            requestHeaders["Accept"]         = new string[] { "application/json", "application/xml" };
            requestHeaders["Content-Length"] = new string[] { "45" };
            var adapter = new HttpMessageHandlerAdapter(next: null, messageHandler: handler, bufferPolicySelector: bufferPolicySelector);

            adapter.Invoke(new OwinContext(environment)).Wait();

            var request = handler.Request;

            Assert.Equal(2, request.Headers.Count());
            Assert.Equal(new string[] { "application/json", "application/xml" }, request.Headers.Accept.Select(mediaType => mediaType.ToString()).ToArray());
            Assert.Equal("localhost", request.Headers.Host);
            Assert.Single(request.Content.Headers);
            Assert.Equal(45, request.Content.Headers.ContentLength);
        }
コード例 #25
0
        public void Invoke_AddsTransferEncodingChunkedHeaderOverContentLength()
        {
            var response = new HttpResponseMessage(HttpStatusCode.OK);

            response.Content = new StreamContent(new MemoryStream(Encoding.UTF8.GetBytes("Hello world")));
            response.Headers.TransferEncodingChunked = true;
            var handler = new HandlerStub()
            {
                Response = response
            };
            var bufferPolicySelector = CreateBufferPolicySelector(bufferInput: false, bufferOutput: false);
            var environment          = CreateOwinEnvironment("GET", "http", "localhost", "/vroot", "/api/customers");
            var adapter = new HttpMessageHandlerAdapter(next: null, messageHandler: handler, bufferPolicySelector: bufferPolicySelector);

            adapter.Invoke(new OwinContext(environment)).Wait();

            var responseHeaders = environment["owin.ResponseHeaders"] as IDictionary <string, string[]>;

            Assert.Equal("chunked", responseHeaders["Transfer-Encoding"][0]);
            Assert.False(responseHeaders.ContainsKey("Content-Length"));
        }
コード例 #26
0
        public void Invoke_SetsResponseHeaders()
        {
            var response = new HttpResponseMessage(HttpStatusCode.OK);

            response.Headers.Location = new Uri("http://www.location.com/");
            response.Content          = new StringContent(@"{""x"":""y""}", Encoding.UTF8, "application/json");
            var handler = new HandlerStub()
            {
                Response = response
            };
            var bufferPolicySelector = CreateBufferPolicySelector(bufferInput: false, bufferOutput: false);
            var environment          = CreateOwinEnvironment("GET", "http", "localhost", "/vroot", "/api/customers");
            var adapter = new HttpMessageHandlerAdapter(next: null, messageHandler: handler, bufferPolicySelector: bufferPolicySelector);

            adapter.Invoke(new OwinContext(environment)).Wait();

            var responseHeaders = environment["owin.ResponseHeaders"] as IDictionary <string, string[]>;

            Assert.Equal(3, responseHeaders.Count);
            Assert.Equal("http://www.location.com/", Assert.Single(responseHeaders["Location"]));
            Assert.Equal("9", Assert.Single(responseHeaders["Content-Length"]));
            Assert.Equal("application/json; charset=utf-8", Assert.Single(responseHeaders["Content-Type"]));
        }
        public void Invoke_CallsMessageHandler_WithEnvironmentCancellationToken()
        {
            var handler = CreateOKHandlerStub();
            var bufferPolicySelector = CreateBufferPolicySelector(bufferInput: false, bufferOutput: false);
            var environment = CreateEnvironment("GET", "http", "localhost", "/vroot", "/api/customers");
            var cancellationToken = new CancellationToken();
            environment["owin.CallCancelled"] = cancellationToken;
            var adapter = new HttpMessageHandlerAdapter(env => TaskHelpers.Completed(), handler, bufferPolicySelector);

            adapter.Invoke(environment).Wait();

            Assert.Equal(cancellationToken, handler.CancellationToken);
        }
コード例 #28
0
 public static Func<IDictionary<string, object>, Task> CreateWebApiAppFunc(HttpConfiguration config)
 {
     var app = new HttpServer(config);
     var options = new HttpMessageHandlerOptions()
     {
         MessageHandler = app,
         BufferPolicySelector = new OwinBufferPolicySelector(),
         ExceptionLogger = new WebApiExceptionLogger(),
         ExceptionHandler = new WebApiExceptionHandler()
     };
     var handler = new HttpMessageHandlerAdapter(null, options);
     return (env) => handler.Invoke(new OwinContext(env));
 }
        public void Invoke_AddsTransferEncodingChunkedHeaderOverContentLength()
        {
            var response = new HttpResponseMessage(HttpStatusCode.OK);
            response.Content = new StreamContent(new MemoryStream(Encoding.UTF8.GetBytes("Hello world")));
            response.Headers.TransferEncodingChunked = true;
            var handler = new HandlerStub() { Response = response };
            var bufferPolicySelector = CreateBufferPolicySelector(bufferInput: false, bufferOutput: false);
            var environment = CreateEnvironment("GET", "http", "localhost", "/vroot", "/api/customers");
            var adapter = new HttpMessageHandlerAdapter(env => TaskHelpers.Completed(), handler, bufferPolicySelector);

            adapter.Invoke(environment).Wait();

            var responseHeaders = environment["owin.ResponseHeaders"] as IDictionary<string, string[]>;
            Assert.Equal("chunked", responseHeaders["Transfer-Encoding"][0]);
            Assert.False(responseHeaders.ContainsKey("Content-Length"));
        }
        public void Invoke_RespectsOutputBufferingSetting(bool bufferOutput)
        {
            var response = new HttpResponseMessage(HttpStatusCode.OK);
            response.Content = new ObjectContent<string>("blue", new JsonMediaTypeFormatter());
            var handler = new HandlerStub() { Response = response };
            var bufferPolicySelector = CreateBufferPolicySelector(bufferInput: false, bufferOutput: bufferOutput);
            var environment = CreateEnvironment("GET", "http", "localhost", "/vroot", "/api/customers");
            var adapter = new HttpMessageHandlerAdapter(env => TaskHelpers.Completed(), handler, bufferPolicySelector);

            adapter.Invoke(environment).Wait();

            var responseHeaders = environment["owin.ResponseHeaders"] as IDictionary<string, string[]>;
            if (bufferOutput)
            {
                Assert.True(responseHeaders.ContainsKey("Content-Length"));
            }
            else
            {
                Assert.False(responseHeaders.ContainsKey("Content-Length"));
            }            
        }
        public void Invoke_SetsResponseHeaders()
        {
            var response = new HttpResponseMessage(HttpStatusCode.OK);
            response.Headers.Location = new Uri("http://www.location.com/");
            response.Content = new StringContent(@"{""x"":""y""}", Encoding.UTF8, "application/json");
            var handler = new HandlerStub() { Response = response };
            var bufferPolicySelector = CreateBufferPolicySelector(bufferInput: false, bufferOutput: false);
            var environment = CreateEnvironment("GET", "http", "localhost", "/vroot", "/api/customers");
            var adapter = new HttpMessageHandlerAdapter(env => TaskHelpers.Completed(), handler, bufferPolicySelector);

            adapter.Invoke(environment).Wait();

            var responseHeaders = environment["owin.ResponseHeaders"] as IDictionary<string, string[]>;
            Assert.Equal(3, responseHeaders.Count);
            Assert.Equal("http://www.location.com/", Assert.Single(responseHeaders["Location"]));
            Assert.Equal("9", Assert.Single(responseHeaders["Content-Length"]));
            Assert.Equal("application/json; charset=utf-8", Assert.Single(responseHeaders["Content-Type"]));
        }
        public void Invoke_CallsNext_IfMessageHandlerReturns404WithNoRouteMatched()
        {
            bool nextCalled = false;
            var next = new Func<IDictionary<string, object>, Task>(env =>
                {
                    nextCalled = true;
                    return TaskHelpers.Completed();
                });
            HttpResponseMessage response = new HttpResponseMessage(HttpStatusCode.NotFound);
            var handler = new HandlerStub() { Response = response, AddNoRouteMatchedKey = true };
            var bufferPolicySelector = CreateBufferPolicySelector(bufferInput: false, bufferOutput: false);
            var environment = CreateEnvironment("GET", "http", "localhost", "/vroot", "/api/customers");
            var adapter = new HttpMessageHandlerAdapter(next, handler, bufferPolicySelector);

            adapter.Invoke(environment).Wait();

            Assert.True(nextCalled);
        }
        // Disabled tests until we can rely on a Microsoft.Owin implementation that provides a
        // URI that handles the following encoded characters: % \ ? #
        // Tracked by https://aspnetwebstack.codeplex.com/workitem/1054
        //[InlineData("%24")]
        //[InlineData(@"\")]
        //[InlineData("?#")]
        public void Invoke_CreatesUri_ThatGeneratesCorrectlyDecodedStrings(string decodedId)
        {
            var handler = CreateOKHandlerStub();
            var bufferPolicySelector = CreateBufferPolicySelector(bufferInput: false, bufferOutput: false);
            var environment = CreateEnvironment("GET", "http", "localhost", "/vroot", "/api/customers/" + decodedId);
            var adapter = new HttpMessageHandlerAdapter(env => TaskHelpers.Completed(), handler, bufferPolicySelector);
            var route = new HttpRoute("api/customers/{id}");
            
            adapter.Invoke(environment).Wait();
            IHttpRouteData routeData = route.GetRouteData("/vroot", handler.Request);

            Assert.NotNull(routeData);
            Assert.Equal(decodedId, routeData.Values["id"]);
        }
コード例 #34
0
        public void Invoke_CallsNext_IfMessageHandlerReturns404WithNoRouteMatched()
        {
            var nextMock = new Mock<OwinMiddleware>(null);
            nextMock.Setup(middleware => middleware.Invoke(It.IsAny<OwinContext>())).Returns(TaskHelpers.Completed()).Verifiable();
            HttpResponseMessage response = new HttpResponseMessage(HttpStatusCode.NotFound);
            var handler = new HandlerStub() { Response = response, AddNoRouteMatchedKey = true };
            var bufferPolicySelector = CreateBufferPolicySelector(bufferInput: false, bufferOutput: false);
            var environment = CreateOwinEnvironment("GET", "http", "localhost", "/vroot", "/api/customers");
            var adapter = new HttpMessageHandlerAdapter(next: nextMock.Object, messageHandler: handler, bufferPolicySelector: bufferPolicySelector);

            adapter.Invoke(new OwinContext(environment)).Wait();

            nextMock.Verify();
        }
コード例 #35
0
        public void Invoke_DoesNotCallNext_IfMessageHandlerDoesNotAddNoRouteMatchedProperty()
        {
            var mockNext = new Mock<OwinMiddleware>(MockBehavior.Strict, null);
            HttpResponseMessage response = new HttpResponseMessage(HttpStatusCode.NotFound);
            var handler = new HandlerStub() { Response = response, AddNoRouteMatchedKey = false };
            var bufferPolicySelector = CreateBufferPolicySelector(bufferInput: false, bufferOutput: false);
            var environment = CreateOwinEnvironment("GET", "http", "localhost", "/vroot", "/api/customers");
            var adapter = new HttpMessageHandlerAdapter(next: mockNext.Object, messageHandler: handler, bufferPolicySelector: bufferPolicySelector);

            Assert.DoesNotThrow(
                () => adapter.Invoke(new OwinContext(environment)).Wait());
        }
コード例 #36
0
        public void Invoke_SetsOwinRequestContext()
        {
            // Arrange
            IHostBufferPolicySelector bufferPolicySelector = CreateBufferPolicySelector(bufferInput: false,
                bufferOutput: false);

            using (HttpResponseMessage response = new HttpResponseMessage())
            {
                HttpRequestMessage request = null;
                Func<HttpRequestMessage, CancellationToken, Task<HttpResponseMessage>> sendAsync = (r, c) =>
                {
                    request = r;
                    return Task.FromResult(response);
                };

                using (HttpMessageHandler messageHandler = new LambdaHttpMessageHandler(sendAsync))
                using (HttpMessageHandlerAdapter adapter = new HttpMessageHandlerAdapter(next: null,
                    messageHandler: messageHandler, bufferPolicySelector: bufferPolicySelector))
                {
                    Mock<IHeaderDictionary> requestHeadersMock = new Mock<IHeaderDictionary>(MockBehavior.Strict);
                    requestHeadersMock.Setup(h => h.GetEnumerator()).Returns(
                        new Mock<IEnumerator<KeyValuePair<string, string[]>>>().Object);

                    Mock<IOwinRequest> requestMock = new Mock<IOwinRequest>(MockBehavior.Strict);
                    requestMock.Setup(r => r.Method).Returns("GET");
                    requestMock.Setup(r => r.Uri).Returns(new Uri("http://ignore"));
                    requestMock.Setup(r => r.Body).Returns(Stream.Null);
                    requestMock.Setup(r => r.Headers).Returns(requestHeadersMock.Object);
                    requestMock.Setup(r => r.User).Returns((IPrincipal)null);
                    requestMock.Setup(r => r.CallCancelled).Returns(CancellationToken.None);

                    Mock<IHeaderDictionary> responseHeadersMock = new Mock<IHeaderDictionary>();

                    Mock<IOwinResponse> responseMock = new Mock<IOwinResponse>();
                    responseMock.Setup(r => r.Headers).Returns(responseHeadersMock.Object);

                    Mock<IOwinContext> contextMock = new Mock<IOwinContext>(MockBehavior.Strict);
                    contextMock.Setup(c => c.Request).Returns(requestMock.Object);
                    contextMock.Setup(c => c.Response).Returns(responseMock.Object);
                    IOwinContext expectedContext = contextMock.Object;

                    // Act
                    adapter.Invoke(expectedContext).Wait();

                    // Assert
                    HttpRequestContext requestContext = request.GetRequestContext();
                    Assert.IsType<OwinHttpRequestContext>(requestContext);
                    OwinHttpRequestContext typedContext = (OwinHttpRequestContext)requestContext;
                    Assert.Same(expectedContext, typedContext.Context);
                    Assert.Same(request, typedContext.Request);
                }
            }
        }
        public void Invoke_CallsMessageHandler_WithEnvironmentUser()
        {
            var handler = CreateOKHandlerStub();
            var bufferPolicySelector = CreateBufferPolicySelector(bufferInput: false, bufferOutput: false);
            var environment = CreateEnvironment("GET", "http", "localhost", "/vroot", "/api/customers");
            var user = new Mock<IPrincipal>().Object;
            environment["server.User"] = user;
            var adapter = new HttpMessageHandlerAdapter(env => TaskHelpers.Completed(), handler, bufferPolicySelector);

            adapter.Invoke(environment).Wait();

            Assert.Equal(user, handler.User);
        }
        public void Invoke_Throws_IfMessageHandlerReturnsNull()
        {
            HttpResponseMessage response = null;
            var handler = new HandlerStub() { Response = response };
            var bufferPolicySelector = CreateBufferPolicySelector(bufferInput: false, bufferOutput: false);
            var environment = CreateEnvironment("GET", "http", "localhost", "/vroot", "/api/customers");
            var adapter = new HttpMessageHandlerAdapter(env => TaskHelpers.Completed(), handler, bufferPolicySelector);

            Assert.Throws<InvalidOperationException>(
                () => adapter.Invoke(environment).Wait(),
                "The message handler did not return a response message.");
        }
        public void Invoke_AddsRequestHeadersToRequestMessage()
        {
            var handler = CreateOKHandlerStub();
            var bufferPolicySelector = CreateBufferPolicySelector(bufferInput: false, bufferOutput: false);
            var environment = CreateEnvironment("GET", "http", "localhost", "/vroot", "/api/customers");
            var requestHeaders = environment["owin.RequestHeaders"] as IDictionary<string, string[]>;
            requestHeaders["Accept"] = new string[] { "application/json", "application/xml" };
            requestHeaders["Content-Length"] = new string[] { "45" };
            var adapter = new HttpMessageHandlerAdapter(env => TaskHelpers.Completed(), handler, bufferPolicySelector);

            adapter.Invoke(environment).Wait();

            var request = handler.Request;
            Assert.Equal(2, request.Headers.Count());
            Assert.Equal(new string[] { "application/json", "application/xml" }, request.Headers.Accept.Select(mediaType => mediaType.ToString()).ToArray());
            Assert.Equal("localhost", request.Headers.Host);
            Assert.Single(request.Content.Headers);
            Assert.Equal(45, request.Content.Headers.ContentLength);
        }
        public void Invoke_SetsResponseStatusCodeAndReasonPhrase()
        {
            var expectedReasonPhrase = "OH NO!";
            var response = new HttpResponseMessage(HttpStatusCode.ServiceUnavailable) { ReasonPhrase = expectedReasonPhrase };
            var handler = new HandlerStub() { Response = response };
            var bufferPolicySelector = CreateBufferPolicySelector(bufferInput: false, bufferOutput: false);
            var environment = CreateEnvironment("GET", "http", "localhost", "/vroot", "/api/customers");
            var adapter = new HttpMessageHandlerAdapter(env => TaskHelpers.Completed(), handler, bufferPolicySelector);

            adapter.Invoke(environment).Wait();

            Assert.Equal(HttpStatusCode.ServiceUnavailable, environment["owin.ResponseStatusCode"]);
            Assert.Equal(expectedReasonPhrase, environment["owin.ResponseReasonPhrase"]);
        }
        public void Invoke_SetsRequestBodyOnRequestMessage()
        {
            var handler = CreateOKHandlerStub();
            var bufferPolicySelector = CreateBufferPolicySelector(bufferInput: false, bufferOutput: false);
            var environment = CreateEnvironment("GET", "http", "localhost", "/vroot", "/api/customers");
            var expectedBody = "This is the request body.";
            environment["owin.RequestBody"] = new MemoryStream(Encoding.UTF8.GetBytes(expectedBody));
            var adapter = new HttpMessageHandlerAdapter(env => TaskHelpers.Completed(), handler, bufferPolicySelector);

            adapter.Invoke(environment).Wait();

            var request = handler.Request;
            Assert.Equal(expectedBody, request.Content.ReadAsStringAsync().Result);
        }
        public void Invoke_SetsResponseBody()
        {
            var response = new HttpResponseMessage(HttpStatusCode.OK);
            var expectedBody = @"{""x"":""y""}";
            response.Content = new StringContent(expectedBody, Encoding.UTF8, "application/json");
            var handler = new HandlerStub() { Response = response };
            var bufferPolicySelector = CreateBufferPolicySelector(bufferInput: false, bufferOutput: false);
            var environment = CreateEnvironment("GET", "http", "localhost", "/vroot", "/api/customers");
            var responseStream = new MemoryStream();
            environment["owin.ResponseBody"] = responseStream;
            var adapter = new HttpMessageHandlerAdapter(env => TaskHelpers.Completed(), handler, bufferPolicySelector);

            adapter.Invoke(environment).Wait();

            responseStream.Seek(0, SeekOrigin.Begin);
            byte[] bodyBytes = new byte[9];
            int charsRead = responseStream.Read(bodyBytes, 0, 9);
            // Assert that we can read 9 characters and no more characters after that
            Assert.Equal(9, charsRead);
            Assert.Equal(-1, responseStream.ReadByte());
            Assert.Equal(expectedBody, Encoding.UTF8.GetString(bodyBytes));
        }
        public void Invoke_RespectsInputBufferingSetting(bool bufferInput)
        {
            var handler = CreateOKHandlerStub();
            var bufferPolicySelector = CreateBufferPolicySelector(bufferInput: bufferInput, bufferOutput: false);
            var environment = CreateEnvironment("GET", "http", "localhost", "/vroot", "/api/customers");
            var expectedBody = "This is the request body.";
            var requestBodyMock = new Mock<MemoryStream>(Encoding.UTF8.GetBytes(expectedBody));
            requestBodyMock.CallBase = true;
            requestBodyMock.Setup(s => s.CanSeek).Returns(false);
            MemoryStream requestBody = requestBodyMock.Object;
            environment["owin.RequestBody"] = requestBody;
            var adapter = new HttpMessageHandlerAdapter(env => TaskHelpers.Completed(), handler, bufferPolicySelector);

            adapter.Invoke(environment).Wait();

            if (bufferInput)
            {
                Assert.False(requestBody.CanRead);
                // Assert that the OWIN environment still has a request body that can be read
                var owinRequestBody = environment["owin.RequestBody"] as Stream;
                byte[] bodyBytes = new byte[25];
                int charsRead = owinRequestBody.Read(bodyBytes, 0, 25);
                Assert.Equal(expectedBody, Encoding.UTF8.GetString(bodyBytes));
            }
            else
            {
                Assert.True(requestBody.CanRead);
            }
            // Assert that Web API gets the right body
            var request = handler.Request;
            Assert.Equal(expectedBody, request.Content.ReadAsStringAsync().Result);

        }
        public void Invoke_AddsZeroContentLengthHeader_WhenThereIsNoContent()
        {
            var response = new HttpResponseMessage(HttpStatusCode.OK);
            var handler = new HandlerStub() { Response = response };
            var bufferPolicySelector = CreateBufferPolicySelector(bufferInput: false, bufferOutput: false);
            var environment = CreateEnvironment("GET", "http", "localhost", "/vroot", "/api/customers");
            var adapter = new HttpMessageHandlerAdapter(env => TaskHelpers.Completed(), handler, bufferPolicySelector);

            adapter.Invoke(environment).Wait();

            var responseHeaders = environment["owin.ResponseHeaders"] as IDictionary<string, string[]>;
            Assert.Equal("0", responseHeaders["Content-Length"][0]);
        }
        public void Invoke_SetsOwinEnvironment()
        {
            var handler = CreateOKHandlerStub();
            var bufferPolicySelector = CreateBufferPolicySelector(bufferInput: false, bufferOutput: false);
            var environment = CreateEnvironment("GET", "http", "localhost", "/vroot", "/api/customers");
            var adapter = new HttpMessageHandlerAdapter(env => TaskHelpers.Completed(), handler, bufferPolicySelector);

            adapter.Invoke(environment).Wait();

            var request = handler.Request;
            Assert.Same(environment, request.GetOwinEnvironment());
        }
        public void Invoke_AddsTransferEncodingChunkedHeaderIfThereIsNoContentLength()
        {
            var response = new HttpResponseMessage(HttpStatusCode.OK);
            response.Content = new ObjectContent<string>("blue", new JsonMediaTypeFormatter());
            var handler = new HandlerStub() { Response = response };
            var bufferPolicySelector = CreateBufferPolicySelector(bufferInput: false, bufferOutput: false);
            var environment = CreateEnvironment("GET", "http", "localhost", "/vroot", "/api/customers");
            var adapter = new HttpMessageHandlerAdapter(env => TaskHelpers.Completed(), handler, bufferPolicySelector);

            adapter.Invoke(environment).Wait();

            var responseHeaders = environment["owin.ResponseHeaders"] as IDictionary<string, string[]>;
            Assert.Equal("chunked", responseHeaders["Transfer-Encoding"][0]);
            Assert.False(responseHeaders.ContainsKey("Content-Length"));
        }
        public void Invoke_SetsRequestIsLocalProperty(bool? isLocal, bool expectedRequestLocal)
        {
            var handler = CreateOKHandlerStub();
            var bufferPolicySelector = CreateBufferPolicySelector(bufferInput: false, bufferOutput: false);
            var environment = CreateEnvironment("GET", "http", "localhost", "/vroot", "/api/customers");
            if (isLocal.HasValue)
            {
                environment["server.IsLocal"] = isLocal.Value;
            }
            var adapter = new HttpMessageHandlerAdapter(env => TaskHelpers.Completed(), handler, bufferPolicySelector);

            adapter.Invoke(environment).Wait();

            var request = handler.Request;
            Assert.Equal(expectedRequestLocal, request.IsLocal());
        }
コード例 #48
0
        public void Invoke_SetsOwinEnvironment()
        {
            var handler = CreateOKHandlerStub();
            var bufferPolicySelector = CreateBufferPolicySelector(bufferInput: false, bufferOutput: false);
            var environment = CreateOwinEnvironment("GET", "http", "localhost", "/vroot", "/api/customers");
            var adapter = new HttpMessageHandlerAdapter(next: null, messageHandler: handler, bufferPolicySelector: bufferPolicySelector);

            adapter.Invoke(new OwinContext(environment)).Wait();

            var request = handler.Request;
            Assert.Same(environment, request.GetOwinEnvironment());
        }
        public void Invoke_SetsClientCertificate()
        {
            var handler = CreateOKHandlerStub();
            var bufferPolicySelector = CreateBufferPolicySelector(bufferInput: false, bufferOutput: false);
            var environment = CreateEnvironment("GET", "http", "localhost", "/vroot", "/api/customers");
            var clientCert = new Mock<X509Certificate2>().Object;
            environment["ssl.ClientCertificate"] = clientCert;
            var adapter = new HttpMessageHandlerAdapter(env => TaskHelpers.Completed(), handler, bufferPolicySelector);

            adapter.Invoke(environment).Wait();

            var request = handler.Request;
            Assert.Equal(clientCert, request.GetClientCertificate());
        }