public virtual async Task Overridden_WriteToStreamAsyncWithCancellationToken_GetsCalled()
        {
            // Arrange
            Stream stream = new MemoryStream();
            Mock<TFormatter> formatter = CreateMockFormatter();
            ObjectContent<int> content = new ObjectContent<int>(42, formatter.Object);

            formatter
                .Setup(
                    f =>
                        f.WriteToStreamAsync(
                            typeof(int),
                            42,
                            stream,
                            content,
                            null /* transportContext */
                            ,
                            CancellationToken.None
                        )
                )
                .Returns(TaskHelpers.Completed())
                .Verifiable();

            // Act
            await content.CopyToAsync(stream);

            // Assert
            formatter.Verify();
        }
示例#2
0
        public async Task Headers_ReservedHeaders_PassedThrough()
        {
            OwinHttpListener listener = CreateServer(
                env =>
            {
                var responseHeaders = env.Get <IDictionary <string, string[]> >("owin.ResponseHeaders");
                env.Add("owin.ResponseProtocol", "HTTP/1.0");
                responseHeaders.Add("KEEP-alive", new string[] { "TRUE" });
                responseHeaders.Add("content-length", new string[] { "0" });
                responseHeaders.Add("www-Authenticate", new string[] { "Basic", "NTLM" });
                return(TaskHelpers.Completed());
            },
                HttpServerAddress);

            using (listener)
            {
                var client = new HttpClient();
                HttpResponseMessage response = await client.GetAsync(HttpClientAddress);

                Assert.Equal(HttpStatusCode.OK, response.StatusCode);
                Assert.Equal(3, response.Headers.Count()); // Date, Server
                Assert.Equal(0, response.Content.Headers.ContentLength);
                Assert.Equal(2, response.Headers.WwwAuthenticate.Count());

                // The client does not expose KeepAlive
            }
        }
示例#3
0
        public async Task OwinHttpListenerResponse_101ResponseWithBody_BodyIgnoredByClient()
        {
            OwinHttpListener listener = CreateServer(
                env =>
            {
                env["owin.ResponseStatusCode"] = 101;
                var responseStream             = env.Get <Stream>("owin.ResponseBody");

                var responseHeaders = env.Get <IDictionary <string, string[]> >("owin.ResponseHeaders");
                responseHeaders["content-length"] = new string[] { "10" };

                responseStream.Write(new byte[10], 0, 10);
                return(TaskHelpers.Completed());
            },
                HttpServerAddress);

            using (listener)
            {
                var client = new HttpClient();
                HttpResponseMessage response = await client.GetAsync(HttpClientAddress);

                Assert.Equal(HttpStatusCode.SwitchingProtocols, response.StatusCode);
                Assert.Equal("Switching Protocols", response.ReasonPhrase);
                Assert.Equal(2, response.Headers.Count()); // Date, Server
                Assert.True(response.Headers.Date.HasValue);
                Assert.Equal(1, response.Headers.Server.Count);
                Assert.Equal(0, (await response.Content.ReadAsByteArrayAsync()).Length);
            }
        }
示例#4
0
        public override Task WriteToStreamAsync(Type type, object value, Stream writeStream, HttpContent content, TransportContext transportContext)
        {
            if (type == null)
            {
                throw Error.ArgumentNull("type");
            }

            if (writeStream == null)
            {
                throw Error.ArgumentNull("writeStream");
            }

#if !NETFX_CORE // No DataContractJsonSerializer in portable library version
            if (UseDataContractJsonSerializer && Indent)
            {
                throw Error.NotSupported(Properties.Resources.UnsupportedIndent, typeof(DataContractJsonSerializer));
            }
#endif

            try
            {
                WriteToStream(type, value, writeStream, content);
                return(TaskHelpers.Completed());
            }
            catch (Exception e)
            {
                return(TaskHelpers.FromError(e));
            }
        }
        public override Task WriteToStreamAsync(Type type, object value, Stream writeStream, HttpContent content,
                                                TransportContext transportContext, CancellationToken cancellationToken)
        {
            if (type == null)
            {
                throw Error.ArgumentNull("type");
            }
            if (writeStream == null)
            {
                throw Error.ArgumentNull("writeStream");
            }
            if (Request == null)
            {
                throw Error.InvalidOperation(SRResources.WriteToStreamAsyncMustHaveRequest);
            }
            if (cancellationToken.IsCancellationRequested)
            {
                return(TaskHelpers.Canceled());
            }

            HttpContentHeaders contentHeaders = content == null ? null : content.Headers;

            try
            {
                WriteToStream(type, value, writeStream, content, contentHeaders);
                return(TaskHelpers.Completed());
            }
            catch (Exception ex)
            {
                return(TaskHelpers.FromError(ex));
            }
        }
示例#6
0
        public void LeadingQuestionMarkInQueryIsRemoved()
        {
            /* http://katanaproject.codeplex.com/workitem/22
             *
             * Summary
             *
             * The owin spec for the "owin.RequestQueryString" key:
             *
             *    A string containing the query string component of the HTTP request URI,
             *    without the leading “?” (e.g., "foo=bar&baz=quux"). The value may be an
             *    empty string.
             *
             *  request.RequestUri.Query does not remove the leading '?'. This causes
             *  problems with hosts that then subsequently join the path and querystring
             *  resulting in a '??' (such as signalr converting the env dict to a ServerRequest)
             */

            IDictionary <string, object> env = null;
            var handler = new OwinClientHandler(dict =>
            {
                env = dict;
                return(TaskHelpers.Completed());
            });
            var    httpClient = new HttpClient(handler);
            string query      = "a=b";

            httpClient.GetAsync("http://example.com?" + query).Wait();
            Assert.Equal(query, env["owin.RequestQueryString"]);
        }
示例#7
0
        /// <inheritdoc />
        public Task ChallengeAsync(
            HttpAuthenticationChallengeContext context,
            CancellationToken cancellationToken
            )
        {
            if (context == null)
            {
                throw new ArgumentNullException("context");
            }

            HttpRequestMessage request = context.Request;

            if (request == null)
            {
                throw new InvalidOperationException(
                          OwinResources.HttpAuthenticationChallengeContext_RequestMustNotBeNull
                          );
            }

            IAuthenticationManager authenticationManager = GetAuthenticationManagerOrThrow(request);

            // Control the challenges that OWIN middleware adds later.
            authenticationManager.AuthenticationResponseChallenge = AddChallengeAuthenticationType(
                authenticationManager.AuthenticationResponseChallenge,
                _authenticationType
                );

            return(TaskHelpers.Completed());
        }
        public override Task WriteToStreamAsync_UsesCorrectCharacterEncoding(
            string content,
            string encoding,
            bool isDefaultEncoding
            )
        {
            // DataContractJsonSerializer does not honor the value of byteOrderMark in the UnicodeEncoding ctor.
            // It doesn't include the BOM when byteOrderMark is set to true.
            if (!isDefaultEncoding || encoding != "utf-8")
            {
                // XmlDictionaryReader/Writer only supports utf-8 and 16
                return(TaskHelpers.Completed());
            }

            // Arrange
            DataContractJsonMediaTypeFormatter formatter = new DataContractJsonMediaTypeFormatter();
            string formattedContent = "\"" + content + "\"";
            string mediaType        = string.Format("application/json; charset={0}", encoding);

            // Act & assert
            return(WriteContentUsingCorrectCharacterEncodingHelperAsync(
                       formatter,
                       content,
                       formattedContent,
                       mediaType,
                       encoding,
                       isDefaultEncoding
                       ));
        }
示例#9
0
        public override Task Invoke(IOwinContext context)
        {
            try
            {
                return(Next.Invoke(context).ContinueWith(appTask =>
                {
                    if (appTask.IsFaulted)
                    {
                        return DisplayExceptionWrapper(context, appTask.Exception);
                    }
                    if (appTask.IsCanceled)
                    {
                        return DisplayExceptionWrapper(context, new TaskCanceledException(appTask));
                    }
                    return TaskHelpers.Completed();
                }));
            }
            catch (Exception ex)
            {
                // If there's a Exception while generating the error page, re-throw the original exception.
                try
                {
                    return(DisplayException(context, ex));
                }
                catch (Exception)
                {
                }

                throw;
            }
        }
        private static Task SendResponseMessageAsync(HttpResponseMessage response, IOwinResponse owinResponse)
        {
            owinResponse.StatusCode   = (int)response.StatusCode;
            owinResponse.ReasonPhrase = response.ReasonPhrase;

            // Copy non-content headers
            IDictionary <string, string[]> responseHeaders = owinResponse.Headers;

            foreach (KeyValuePair <string, IEnumerable <string> > header in response.Headers)
            {
                responseHeaders[header.Key] = header.Value.AsArray();
            }

            HttpContent responseContent = response.Content;

            if (responseContent == null)
            {
                // Set the content-length to 0 to prevent the server from sending back the response chunked
                responseHeaders["Content-Length"] = new string[] { "0" };
                return(TaskHelpers.Completed());
            }
            else
            {
                // Copy content headers
                foreach (KeyValuePair <string, IEnumerable <string> > contentHeader in responseContent.Headers)
                {
                    responseHeaders[contentHeader.Key] = contentHeader.Value.AsArray();
                }

                // Copy body
                return(responseContent.CopyToAsync(owinResponse.Body));
            }
        }
        public override Task ReadFromStreamAsync_UsesCorrectCharacterEncoding(
            string content,
            string encoding,
            bool isDefaultEncoding
            )
        {
            if (!isDefaultEncoding)
            {
                // XmlDictionaryReader/Writer only supports utf-8 and 16
                return(TaskHelpers.Completed());
            }

            // Arrange
            DataContractJsonMediaTypeFormatter formatter = new DataContractJsonMediaTypeFormatter();
            string formattedContent = "\"" + content + "\"";
            string mediaType        = string.Format("application/json; charset={0}", encoding);

            // Act & assert
            return(ReadContentUsingCorrectCharacterEncodingHelperAsync(
                       formatter,
                       content,
                       formattedContent,
                       mediaType,
                       encoding,
                       isDefaultEncoding
                       ));
        }
示例#12
0
        public async Task ExecuteExceptionFilterAsync_Traces()
        {
            // Arrange
            HttpRequestMessage      request    = new HttpRequestMessage();
            HttpResponseMessage     response   = new HttpResponseMessage();
            Mock <IExceptionFilter> mockFilter = new Mock <IExceptionFilter>()
            {
                CallBase = true
            };

            mockFilter.Setup(f => f.ExecuteExceptionFilterAsync(It.IsAny <HttpActionExecutedContext>(), It.IsAny <CancellationToken>()))
            .Returns(TaskHelpers.Completed());
            HttpActionExecutedContext actionExecutedContext = ContextUtil.GetActionExecutedContext(request, response);
            TestTraceWriter           traceWriter           = new TestTraceWriter();
            ExceptionFilterTracer     tracer = new ExceptionFilterTracer(mockFilter.Object, traceWriter);

            TraceRecord[] expectedTraces = new TraceRecord[]
            {
                new TraceRecord(request, TraceCategories.FiltersCategory, TraceLevel.Info)
                {
                    Kind = TraceKind.Begin, Operation = "ExecuteExceptionFilterAsync"
                },
                new TraceRecord(request, TraceCategories.FiltersCategory, TraceLevel.Info)
                {
                    Kind = TraceKind.End, Operation = "ExecuteExceptionFilterAsync"
                },
            };

            // Act
            var filter = (IExceptionFilter)tracer;
            await filter.ExecuteExceptionFilterAsync(actionExecutedContext, CancellationToken.None);

            // Assert
            Assert.Equal <TraceRecord>(expectedTraces, traceWriter.Traces, new TraceRecordComparer());
        }
 public void KnownStagesSpecified(IAppBuilder app)
 {
     app.UseErrorPage();
     app.Use <BreadCrumbMiddleware>("a", "Authenticate");
     AddStageMarker(app, "Authenticate");
     app.Use <BreadCrumbMiddleware>("b", "PostAuthenticate");
     AddStageMarker(app, "PostAuthenticate");
     app.Use <BreadCrumbMiddleware>("c", "Authorize");
     AddStageMarker(app, "Authorize");
     app.Use <BreadCrumbMiddleware>("d", "PostAuthorize");
     AddStageMarker(app, "PostAuthorize");
     app.Use <BreadCrumbMiddleware>("e", "ResolveCache");
     AddStageMarker(app, "ResolveCache");
     app.Use <BreadCrumbMiddleware>("f", "PostResolveCache");
     AddStageMarker(app, "PostResolveCache");
     app.Use <BreadCrumbMiddleware>("g", "MapHandler");
     AddStageMarker(app, "MapHandler");
     app.Use <BreadCrumbMiddleware>("h", "PostMapHandler");
     AddStageMarker(app, "PostMapHandler");
     app.Use <BreadCrumbMiddleware>("i", "AcquireState");
     AddStageMarker(app, "AcquireState");
     app.Use <BreadCrumbMiddleware>("j", "PostAcquireState");
     AddStageMarker(app, "PostAcquireState");
     app.Use <BreadCrumbMiddleware>("k", "PreHandlerExecute");
     AddStageMarker(app, "PreHandlerExecute");
     app.Run(context =>
     {
         var fullBreadCrumb = context.Get <string>("test.BreadCrumb");
         Assert.Equal("abcdefghijk", fullBreadCrumb);
         return(TaskHelpers.Completed());
     });
 }
示例#14
0
        public void SetSpecialHeadersApp(IAppBuilder app)
        {
            app.UseErrorPage(new ErrorPageOptions()
            {
                ShowExceptionDetails = true
            });
            app.Run(context =>
            {
                IHeaderDictionary responseHeaders = context.Response.Headers;
                foreach (var header in _specialHeaders)
                {
                    responseHeaders[header.Key] = header.Value;
                    Assert.True(responseHeaders.ContainsKey(header.Key), header.Key);
                    Assert.Equal(header.Value, responseHeaders[header.Key]);
                }

                Assert.Equal(_specialHeaders.Length, responseHeaders.Count);
                Assert.Equal(_specialHeaders.Length, responseHeaders.Count());

                // All show up in enumeration?
                foreach (var specialPair in _specialHeaders)
                {
                    Assert.True(responseHeaders.Select(pair => pair.Key)
                                .Contains(specialPair.Key), specialPair.Key);
                }

                context.Response.StatusCode = ExpectedStatusCode;

                // Some header issues are only visible after calling write and flush.
                context.Response.Write("Hello World");
                context.Response.Body.Flush();
                return(TaskHelpers.Completed());
            });
        }
示例#15
0
        internal static Task WriteStreamedResponseContentAsync(HttpResponseBase httpResponseBase, HttpContent responseContent)
        {
            Contract.Assert(httpResponseBase != null);
            Contract.Assert(responseContent != null);

            Task writeResponseContentTask = null;

            try
            {
                // Copy the HttpContent into the output stream asynchronously.
                writeResponseContentTask = responseContent.CopyToAsync(httpResponseBase.OutputStream);
            }
            catch
            {
                // Streamed content may have been written and cannot be recalled.
                // Our only choice is to abort the connection.
                AbortConnection(httpResponseBase);
                return(TaskHelpers.Completed());
            }

            return(writeResponseContentTask
                   .Catch((info) =>
            {
                // Streamed content may have been written and cannot be recalled.
                // Our only choice is to abort the connection.
                AbortConnection(httpResponseBase);
                return info.Handled();
            }));
        }
示例#16
0
        public void Completed_RuturnsCompletedTask()
        {
            Task task = TaskHelpers.Completed();

            Assert.NotNull(task);
            Assert.Equal(TaskStatus.RanToCompletion, task.Status);
        }
 public static Task RunAsync(CefThreadId threadId, Action action)
 {
     if (CefRuntime.CurrentlyOn(threadId))
     {
         action();
         return(TaskHelpers.Completed());
     }
     else
     {
         var tcs = new TaskCompletionSource <FakeVoid>();
         StartNew(threadId, () =>
         {
             try
             {
                 action();
                 tcs.SetResultAsync(default(FakeVoid));
             }
             catch (Exception e)
             {
                 tcs.SetExceptionAsync(e);
             }
         });
         return(tcs.Task);
     }
 }
示例#18
0
        public override Task ReadFromStreamAsync_UsesCorrectCharacterEncoding(string content, string encoding, bool isDefaultEncoding)
        {
            if (!isDefaultEncoding)
            {
                // XmlDictionaryReader/Writer only supports utf-8 and 16
                return(TaskHelpers.Completed());
            }

            // Arrange
            XmlMediaTypeFormatter formatter = new XmlMediaTypeFormatter();

            string formattedContent = "<string xmlns=\"http://schemas.microsoft.com/2003/10/Serialization/\">" + content + "</string>";

#if NETFX_CORE
            // We need to supply the xml declaration when compiled in portable library for non utf-8 content
            if (String.Equals("utf-16", encoding, StringComparison.OrdinalIgnoreCase))
            {
                formattedContent = "<?xml version=\"1.0\" encoding=\"UTF-16\"?>" + formattedContent;
            }
#endif
            string mediaType = string.Format("application/xml; charset={0}", encoding);

            // Act & assert
            return(ReadFromStreamAsync_UsesCorrectCharacterEncodingHelper(formatter, content, formattedContent, mediaType, encoding, isDefaultEncoding));
        }
示例#19
0
        public virtual Task ExecuteBindingAsync(HttpActionContext actionContext, CancellationToken cancellationToken)
        {
            if (_parameterBindings.Length == 0)
            {
                return(TaskHelpers.Completed());
            }

            // First, make sure the actionBinding is valid before trying to execute it. This keeps us in a known state in case of errors.
            foreach (HttpParameterBinding parameterBinder in ParameterBindings)
            {
                if (!parameterBinder.IsValid)
                {
                    // Throwing an exception because the webService developer's action signature is bad.
                    // This exception will be caught and converted into a 500 by the dispatcher
                    return(TaskHelpers.FromError(new InvalidOperationException(parameterBinder.ErrorMessage)));
                }
            }

            if (_metadataProvider == null)
            {
                HttpConfiguration config = actionContext.ControllerContext.Configuration;
                _metadataProvider = config.Services.GetModelMetadataProvider();
            }

            // Execute all the binders.
            IEnumerable <Task> tasks = from parameterBinder in ParameterBindings select parameterBinder.ExecuteBindingAsync(_metadataProvider, actionContext, cancellationToken);

            return(TaskHelpers.Iterate(tasks, cancellationToken, disposeEnumerator: false));
        }
示例#20
0
        public void Completed_ReturnsCompletedTask()
        {
            Task result = TaskHelpers.Completed();

            Assert.NotNull(result);
            Assert.Equal(TaskStatus.RanToCompletion, result.Status);
        }
示例#21
0
        public virtual Task ExecuteBindingAsync(HttpActionContext actionContext, CancellationToken cancellationToken)
        {
            if (_parameterBindings.Length == 0)
            {
                return(TaskHelpers.Completed());
            }

            // First, make sure the actionBinding is valid before trying to execute it. This keeps us in a known state in case of errors.
            foreach (HttpParameterBinding parameterBinder in ParameterBindings)
            {
                if (!parameterBinder.IsValid)
                {
                    // Error code here is 500 because the WebService developer's action signature is bad.
                    return(TaskHelpers.FromError(new HttpResponseException(actionContext.Request.CreateResponse(
                                                                               HttpStatusCode.InternalServerError, parameterBinder.ErrorMessage))));
                }
            }

            if (_metadataProvider == null)
            {
                HttpConfiguration config = actionContext.ControllerContext.Configuration;
                _metadataProvider = config.ServiceResolver.GetModelMetadataProvider();
            }

            // Execute all the binders.
            IEnumerable <Task> tasks = from parameterBinder in ParameterBindings select parameterBinder.ExecuteBindingAsync(_metadataProvider, actionContext, cancellationToken);

            return(TaskHelpers.Iterate(tasks, cancellationToken));
        }
示例#22
0
        public void Normal_request_should_pass_through_unchanged()
        {
            var stack = Build(b => b
                              .UseShowExceptions()
                              .UseFunc <AppFunc>(_ => appEnv =>
            {
                Response appResult = new Response(appEnv)
                {
                    StatusCode = 200
                };
                appResult.Headers.SetHeader("Content-Type", "text/plain");
                appResult.Headers.SetHeader("Content-Length", "5");
                appResult.Write("Hello");
                return(TaskHelpers.Completed());
            }));

            Request      request  = Request.Create();
            Response     response = new Response(request.Environment);
            MemoryStream buffer   = new MemoryStream();

            response.OutputStream = buffer;
            stack(request.Environment).Wait();

            Assert.That(response.StatusCode, Is.EqualTo(200));
            Assert.That(ReadBody(buffer), Is.EqualTo("Hello"));
        }
示例#23
0
        public override Task WriteToStreamAsync(Type type, object value, Stream writeStream, HttpContent content,
                                                TransportContext transportContext, CancellationToken cancellationToken)
        {
            if (type == null)
            {
                throw Error.ArgumentNull("type");
            }
            if (writeStream == null)
            {
                throw Error.ArgumentNull("writeStream");
            }
            if (cancellationToken.IsCancellationRequested)
            {
                return(TaskHelpers.Canceled());
            }

            try
            {
                WriteToStream(type, value, writeStream, content);
                return(TaskHelpers.Completed());
            }
            catch (Exception e)
            {
                return(TaskHelpers.FromError(e));
            }
        }
示例#24
0
        public async Task Body_PostChunkedX_StreamWithXBytes()
        {
            OwinHttpListener listener = CreateServer(
                env =>
            {
                string[] values;
                var requestHeaders = env.Get <IDictionary <string, string[]> >("owin.RequestHeaders");

                Assert.True(requestHeaders.TryGetValue("Transfer-Encoding", out values));
                Assert.Equal(1, values.Length);
                Assert.Equal("chunked", values[0]);

                var requestBody = env.Get <Stream>("owin.RequestBody");
                Assert.NotNull(requestBody);

                var buffer = new MemoryStream();
                requestBody.CopyTo(buffer);
                Assert.Equal(11, buffer.Length);

                return(TaskHelpers.Completed());
            },
                HttpServerAddress);

            var request = new HttpRequestMessage(HttpMethod.Post, HttpClientAddress);

            request.Headers.TransferEncodingChunked = true;
            request.Content = new StringContent("Hello World");
            await SendRequest(listener, request);
        }
示例#25
0
        public async Task Headers_CustomHeaders_PassedThrough()
        {
            OwinHttpListener listener = CreateServer(
                env =>
            {
                var responseHeaders = env.Get <IDictionary <string, string[]> >("owin.ResponseHeaders");
                responseHeaders.Add("Custom1", new string[] { "value1a", "value1b" });
                responseHeaders.Add("Custom2", new string[] { "value2a, value2b" });
                responseHeaders.Add("Custom3", new string[] { "value3a, value3b", "value3c" });
                return(TaskHelpers.Completed());
            },
                HttpServerAddress);

            using (listener)
            {
                var client = new HttpClient();
                HttpResponseMessage response = await client.GetAsync(HttpClientAddress);

                Assert.Equal(HttpStatusCode.OK, response.StatusCode);
                Assert.Equal(5, response.Headers.Count()); // Date, Server

                Assert.Equal(2, response.Headers.GetValues("Custom1").Count());
                Assert.Equal("value1a", response.Headers.GetValues("Custom1").First());
                Assert.Equal("value1b", response.Headers.GetValues("Custom1").Skip(1).First());
                Assert.Equal(1, response.Headers.GetValues("Custom2").Count());
                Assert.Equal("value2a, value2b", response.Headers.GetValues("Custom2").First());
                Assert.Equal(2, response.Headers.GetValues("Custom3").Count());
                Assert.Equal("value3a, value3b", response.Headers.GetValues("Custom3").First());
                Assert.Equal("value3c", response.Headers.GetValues("Custom3").Skip(1).First());
            }
        }
示例#26
0
        public async Task Environment_EmptyGetRequest_RequiredKeysPresentAndCorrect()
        {
            OwinHttpListener listener = CreateServer(
                env =>
            {
                object ignored;
                Assert.True(env.TryGetValue("owin.RequestMethod", out ignored));
                Assert.Equal("GET", env["owin.RequestMethod"]);

                Assert.True(env.TryGetValue("owin.RequestPath", out ignored));
                Assert.Equal("/SubPath", env["owin.RequestPath"]);

                Assert.True(env.TryGetValue("owin.RequestPathBase", out ignored));
                Assert.Equal("/BaseAddress", env["owin.RequestPathBase"]);

                Assert.True(env.TryGetValue("owin.RequestProtocol", out ignored));
                Assert.Equal("HTTP/1.1", env["owin.RequestProtocol"]);

                Assert.True(env.TryGetValue("owin.RequestQueryString", out ignored));
                Assert.Equal("QueryString", env["owin.RequestQueryString"]);

                Assert.True(env.TryGetValue("owin.RequestScheme", out ignored));
                Assert.Equal("http", env["owin.RequestScheme"]);

                Assert.True(env.TryGetValue("owin.Version", out ignored));
                Assert.Equal("1.0", env["owin.Version"]);

                return(TaskHelpers.Completed());
            },
                HttpServerAddress);

            await SendGetRequest(listener, HttpClientAddress + "SubPath?QueryString");
        }
示例#27
0
        public async Task Headers_OtherReservedHeaders_PassedThrough()
        {
            OwinHttpListener listener = CreateServer(
                env =>
            {
                var responseHeaders = env.Get <IDictionary <string, string[]> >("owin.ResponseHeaders");
                responseHeaders.Add("Transfer-Encoding", new string[] { "ChUnKed" });
                responseHeaders.Add("CONNECTION", new string[] { "ClOsE" });
                return(TaskHelpers.Completed());
            },
                HttpServerAddress);

            using (listener)
            {
                var client = new HttpClient();
                HttpResponseMessage response = await client.GetAsync(HttpClientAddress);

                Assert.Equal(HttpStatusCode.OK, response.StatusCode);
                Assert.Equal(4, response.Headers.Count());                             // Date, Server
                Assert.Equal("chunked", response.Headers.TransferEncoding.ToString()); // Normalized by server
                Assert.True(response.Headers.TransferEncodingChunked.Value);
                Assert.Equal("close", response.Headers.Connection.First());            // Normalized by server
                Assert.True(response.Headers.ConnectionClose.Value);
            }
        }
        public Task ItShouldFireOnSendingHeaders()
        {
            var  stateObject           = new object();
            bool onSendingHeadersFired = false;
            bool stateObjectMatched    = false;

            var routes = new RouteCollection();

            routes.MapOwinPath <AppDelegate>(string.Empty,
                                             env =>
            {
                var onSendingHeadersRegister = env.Get <Action <Action <object>, object> >("server.OnSendingHeaders");
                onSendingHeadersRegister(
                    passedObject =>
                {
                    onSendingHeadersFired = true;
                    stateObjectMatched    = object.ReferenceEquals(passedObject, stateObject);
                }, stateObject);
                return(TaskHelpers.Completed());
            });
            RequestContext requestContext = NewRequestContext(routes, NewHttpContext(new Uri("http://localhost/alpha/beta")));

            Task task = ExecuteRequestContext(requestContext);

            return(task.ContinueWith(
                       _ =>
            {
                task.Exception.ShouldBe(null);
                onSendingHeadersFired.ShouldBe(true);
                stateObjectMatched.ShouldBe(true);
            }));
        }
示例#29
0
        public async Task OwinHttpListenerResponse_OnFirstWrite_OnSendingHeaders()
        {
            OwinHttpListener listener = CreateServer(
                env =>
            {
                env["owin.ResponseStatusCode"]   = 200;
                env["owin.ResponseReasonPhrase"] = "Custom";
                var responseStream = env.Get <Stream>("owin.ResponseBody");

                var responseHeaders = env.Get <IDictionary <string, string[]> >("owin.ResponseHeaders");

                env.Get <Action <Action <object>, object> >("server.OnSendingHeaders")(state => responseHeaders["custom-header"] = new string[] { "customvalue" }, null);

                responseHeaders["content-length"] = new string[] { "10" };

                responseStream.Write(new byte[10], 0, 10);

                return(TaskHelpers.Completed());
            },
                HttpServerAddress);

            using (listener)
            {
                var client = new HttpClient();
                HttpResponseMessage response = await client.GetAsync(HttpClientAddress);

                Assert.Equal(HttpStatusCode.OK, response.StatusCode);
                Assert.Equal("Custom", response.ReasonPhrase);
                Assert.Equal(3, response.Headers.Count()); // Date, Server
                Assert.True(response.Headers.Date.HasValue);
                Assert.Equal(1, response.Headers.Server.Count);
                Assert.Equal("customvalue", response.Headers.GetValues("custom-header").First());
                Assert.Equal(10, (await response.Content.ReadAsByteArrayAsync()).Length);
            }
        }
        public async Task BindValuesAsync_Invokes_Inner_And_Traces()
        {
            // Arrange
            bool wasInvoked = false;
            Mock <HttpActionBinding> mockBinder = new Mock <HttpActionBinding>()
            {
                CallBase = true
            };

            mockBinder.Setup(b => b.ExecuteBindingAsync(It.IsAny <HttpActionContext>(), It.IsAny <CancellationToken>()))
            .Callback(() => wasInvoked = true).Returns(TaskHelpers.Completed());

            TestTraceWriter         traceWriter = new TestTraceWriter();
            HttpActionBindingTracer tracer      = new HttpActionBindingTracer(mockBinder.Object, traceWriter);

            TraceRecord[] expectedTraces = new TraceRecord[]
            {
                new TraceRecord(_actionContext.Request, TraceCategories.ModelBindingCategory, TraceLevel.Info)
                {
                    Kind = TraceKind.Begin
                },
                new TraceRecord(_actionContext.Request, TraceCategories.ModelBindingCategory, TraceLevel.Info)
                {
                    Kind = TraceKind.End
                }
            };

            // Act
            await tracer.ExecuteBindingAsync(_actionContext, CancellationToken.None);

            // Assert
            Assert.Equal <TraceRecord>(expectedTraces, traceWriter.Traces, new TraceRecordComparer());
            Assert.True(wasInvoked);
        }