Ejemplo n.º 1
0
        /// <summary>
        /// This adapts HttpRequestMessages to ASP.NET Core requests, dispatches them through the pipeline, and returns the
        /// associated HttpResponseMessage.
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        protected override async Task <HttpResponseMessage> SendAsync(
            HttpRequestMessage request,
            CancellationToken cancellationToken)
        {
            if (request == null)
            {
                throw new ArgumentNullException(nameof(request));
            }

            var state          = new RequestState(request, _pathBase, _application);
            var requestContent = request.Content ?? new StreamContent(Stream.Null);
            var body           = await requestContent.ReadAsStreamAsync();

            if (body.CanSeek)
            {
                // This body may have been consumed before, rewind it.
                body.Seek(0, SeekOrigin.Begin);
            }
            state.Context.HttpContext.Request.Body = body;
            var registration = cancellationToken.Register(state.AbortRequest);

            // Async offload, don't let the test code block the caller.
            var offload = Task.Factory.StartNew(async() =>
            {
                try
                {
                    await _application.ProcessRequestAsync(state.Context);
                    await state.CompleteResponseAsync();
                    state.ServerCleanup(exception: null);
                }
                catch (Exception ex)
                {
                    state.Abort(ex);
                    state.ServerCleanup(ex);
                }
                finally
                {
                    registration.Dispose();
                }
            });

            return(await state.ResponseTask.ConfigureAwait(false));
        }