protected override async Task <HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) { var serverRequest = new TestRequest(Validate.NotNull(nameof(request), request)); var cookiesFromContainer = CookieContainer.GetCookieHeader(serverRequest.Url); if (!string.IsNullOrEmpty(cookiesFromContainer)) { serverRequest.Headers.Add(HttpHeaderNames.Cookie, cookiesFromContainer); } var context = new TestContext(serverRequest) { CancellationToken = cancellationToken, Route = RouteMatch.UnsafeFromRoot(UrlPath.Normalize(serverRequest.Url.AbsolutePath, false)), }; await _handler.HandleContextAsync(context).ConfigureAwait(false); var serverResponse = context.TestResponse; var responseCookies = serverResponse.Headers.Get(HttpHeaderNames.SetCookie); if (!string.IsNullOrEmpty(responseCookies)) { CookieContainer.SetCookies(serverRequest.Url, responseCookies); } var response = new HttpResponseMessage((HttpStatusCode)serverResponse.StatusCode) { RequestMessage = request, Version = serverResponse.ProtocolVersion, ReasonPhrase = serverResponse.StatusDescription, Content = serverResponse.Body == null ? null : new ByteArrayContent(serverResponse.Body), }; foreach (var key in serverResponse.Headers.AllKeys) { var responseHeaderType = GetResponseHeaderType(key); switch (responseHeaderType) { case ResponseHeaderType.Content: response.Content?.Headers.Add(key, serverResponse.Headers.GetValues(key)); break; case ResponseHeaderType.Response: response.Headers.Add(key, serverResponse.Headers.GetValues(key)); break; case ResponseHeaderType.None: break; default: throw SelfCheck.Failure("Unexpected response header type {responseHeaderType}."); } } return(response); }
/// <inheritdoc /> protected override async Task ProcessRequestsAsync(CancellationToken cancellationToken) { while (!cancellationToken.IsCancellationRequested && (Listener?.IsListening ?? false)) { var context = await Listener.GetContextAsync(cancellationToken).ConfigureAwait(false); context.CancellationToken = cancellationToken; context.Route = RouteMatch.UnsafeFromRoot(UrlPath.Normalize(context.Request.Url.AbsolutePath, false)); #pragma warning disable CS4014 // Call is not awaited - of course, it has to run in parallel. Task.Run(() => DoHandleContextAsync(context), cancellationToken); #pragma warning restore CS4014 } }