コード例 #1
0
        private Request CreateGetRequest(Uri uri)
        {
            Request request = _pipeline.CreateRequest();

            request.Headers.Add(HttpHeader.Common.JsonContentType);
            request.Headers.Add(HttpHeader.Common.JsonAccept);
            request.Method = RequestMethod.Get;
            request.Uri.Reset(uri);

            request.Uri.AppendQuery("api-version", _apiVersion);

            return(request);
        }
コード例 #2
0
        private Request CreateClientSecretAuthRequest(string tenantId, string clientId, string clientSecret, string[] scopes)
        {
            Request request = _pipeline.CreateRequest();

            request.Method = RequestMethod.Post;

            request.Headers.Add(HttpHeader.Common.FormUrlEncodedContentType);

            request.UriBuilder.Uri = _options.AuthorityHost;

            request.UriBuilder.AppendPath(tenantId);

            request.UriBuilder.AppendPath("/oauth2/v2.0/token");

            var bodyStr = $"response_type=token&grant_type=client_credentials&client_id={Uri.EscapeDataString(clientId)}&client_secret={Uri.EscapeDataString(clientSecret)}&scope={Uri.EscapeDataString(string.Join(" ", scopes))}";

            ReadOnlyMemory <byte> content = Encoding.UTF8.GetBytes(bodyStr).AsMemory();

            request.Content = HttpPipelineRequestContent.Create(content);

            return(request);
        }
コード例 #3
0
        public async Task SendMultipartformData()
        {
            IFormCollection formCollection = null;

            HttpPipeline httpPipeline = HttpPipelineBuilder.Build(GetOptions());

            using TestServer testServer = new TestServer(
                      context =>
            {
                formCollection = context.Request.Form;
                return(Task.CompletedTask);
            });

            using Request request = httpPipeline.CreateRequest();
            request.Method        = RequestMethod.Put;
            request.Uri.Reset(testServer.Address);

            var content = new MultipartFormDataContent("test_boundary");

            content.Add(RequestContent.Create(Encoding.UTF8.GetBytes("John")), "FirstName", "file_name.txt", new Dictionary <string, string>
            {
                { "Content-Type", "text/plain; charset=utf-8" }
            });
            content.Add(RequestContent.Create(Encoding.UTF8.GetBytes("Doe")), "LastName", "file_name.txt", new Dictionary <string, string>
            {
                { "Content-Type", "text/plain; charset=utf-8" }
            });

            content.ApplyToRequest(request);

            using Response response = await ExecuteRequest(request, httpPipeline);

            Assert.AreEqual(response.Status, 200);
            Assert.AreEqual(formCollection.Files.Count, 2);

            var formData = formCollection.Files.GetEnumerator();

            formData.MoveNext();
            Assert.AreEqual(formData.Current.Name, "FirstName");
            Assert.AreEqual(formData.Current.FileName, "file_name.txt");
            Assert.AreEqual(formData.Current.Headers.Count, 2);
            Assert.AreEqual(formData.Current.ContentType, "text/plain; charset=utf-8");
            Assert.AreEqual(formData.Current.ContentDisposition, "form-data; name=FirstName; filename=file_name.txt");

            formData.MoveNext();
            Assert.AreEqual(formData.Current.Name, "LastName");
            Assert.AreEqual(formData.Current.FileName, "file_name.txt");
            Assert.AreEqual(formData.Current.Headers.Count, 2);
            Assert.AreEqual(formData.Current.ContentType, "text/plain; charset=utf-8");
            Assert.AreEqual(formData.Current.ContentDisposition, "form-data; name=LastName; filename=file_name.txt");
        }
コード例 #4
0
        public async Task DoesntDisposeRequestInSendRequestAsync()
        {
            HttpPipeline httpPipeline = HttpPipelineBuilder.Build(new TestOptions()
            {
                Transport = new MockTransport(new MockResponse(200))
            });

            using MockRequest request = (MockRequest)httpPipeline.CreateRequest();

            MockResponse response = (MockResponse)await httpPipeline.SendRequestAsync(request, default);

            Assert.False(request.IsDisposed);
            Assert.False(response.IsDisposed);
        }
コード例 #5
0
        public async Task CustomClassifierSetsResponseIsError()
        {
            var mockTransport = new MockTransport(
                new MockResponse(404));

            var pipeline = new HttpPipeline(mockTransport, responseClassifier: new CustomResponseClassifier());

            Request request = pipeline.CreateRequest();

            request.Method = RequestMethod.Get;
            request.Uri.Reset(new Uri("https://contoso.a.io"));
            Response response = await pipeline.SendRequestAsync(request, CancellationToken.None);

            Assert.IsFalse(response.IsError);
        }
コード例 #6
0
        public async Task PipelineSetsResponseIsErrorTrue()
        {
            var mockTransport = new MockTransport(
                new MockResponse(500));

            var pipeline = new HttpPipeline(mockTransport);

            Request request = pipeline.CreateRequest();

            request.Method = RequestMethod.Get;
            request.Uri.Reset(new Uri("https://contoso.a.io"));
            Response response = await pipeline.SendRequestAsync(request, CancellationToken.None);

            Assert.IsTrue(response.IsError);
        }
コード例 #7
0
        public async Task Basics()
        {
            var mockTransport = new MockTransport(
                new MockResponse(500),
                new MockResponse(1));

            var pipeline = new HttpPipeline(mockTransport, new [] { new CustomRetryPolicy() });

            var request = pipeline.CreateRequest();

            request.SetRequestLine(HttpPipelineMethod.Get, new Uri("https://contoso.a.io"));
            var response = await pipeline.SendRequestAsync(request, CancellationToken.None);

            Assert.AreEqual(1, response.Status);
        }
コード例 #8
0
        public async Task PipelineSetsResponseIsErrorFalse()
        {
            var mockTransport = new MockTransport(
                new MockResponse(200));

            var pipeline = new HttpPipeline(mockTransport, new[] { new ResponsePropertiesPolicy(ClientOptions.Default) });

            Request request = pipeline.CreateRequest();

            request.Method = RequestMethod.Get;
            request.Uri.Reset(new Uri("https://contoso.a.io"));
            Response response = await pipeline.SendRequestAsync(request, CancellationToken.None);

            Assert.IsFalse(response.IsError());
        }
コード例 #9
0
        public async Task Basics()
        {
            var mockTransport = new MockTransport(
                new MockResponse(500),
                new MockResponse(1));

            var pipeline = new HttpPipeline(mockTransport, new[] {
                new RetryPolicy(RetryMode.Exponential, TimeSpan.Zero, TimeSpan.Zero, 5)
            }, responseClassifier: new CustomResponseClassifier());

            Http.Request request = pipeline.CreateRequest();
            request.SetRequestLine(RequestMethod.Get, new Uri("https://contoso.a.io"));
            Response response = await pipeline.SendRequestAsync(request, CancellationToken.None);

            Assert.AreEqual(1, response.Status);
        }
コード例 #10
0
        private async Task <string> EvaluatePathAsync(string path, CancellationToken cancellationToken)
        {
            Request request = _pipeline.CreateRequest();

            request.Method = RequestMethod.Get;
            request.Uri    = new RequestUriBuilder();
            request.Uri.Reset(new Uri(path));

            Response response = await _pipeline.SendRequestAsync(request, cancellationToken);

            if (response.Status >= 200 && response.Status <= 299)
            {
                return(await GetContentAsync(response.ContentStream, cancellationToken));
            }

            return(null);
        }
コード例 #11
0
        public async Task <Response <ConfigurationSetting> > AddAsync(ConfigurationSetting setting, CancellationToken cancellation = default)
        {
            if (setting == null)
            {
                throw new ArgumentNullException(nameof(setting));
            }
            if (string.IsNullOrEmpty(setting.Key))
            {
                throw new ArgumentNullException($"{nameof(setting)}.{nameof(setting.Key)}");
            }

            Uri uri = BuildUriForKvRoute(setting);

            using (var request = _pipeline.CreateRequest())
            {
                ReadOnlyMemory <byte> content = Serialize(setting);

                request.SetRequestLine(HttpVerb.Put, uri);

                request.AddHeader(IfNoneMatch, "*");
                request.AddHeader(MediaTypeKeyValueApplicationHeader);
                request.AddHeader(HttpHeader.Common.JsonContentType);

                request.Content = HttpPipelineRequestContent.Create(content);

                var response = await _pipeline.SendRequestAsync(request, cancellation).ConfigureAwait(false);

                if (response.Status == 200 || response.Status == 201)
                {
                    return(await CreateResponse(response, cancellation));
                }
                else
                {
                    throw new RequestFailedException(response);
                }
            }
        }
コード例 #12
0
        private async Task <Response> SendRequest(bool isSeekable, bool isError, Action <MockResponse> setupRequest = null, int maxLength = int.MaxValue)
        {
            var mockResponse = new MockResponse(isError ? 500: 200);

            byte[] responseContent = Encoding.UTF8.GetBytes("Hello world");
            if (isSeekable)
            {
                mockResponse.ContentStream = new MemoryStream(responseContent);
            }
            else
            {
                mockResponse.ContentStream = new NonSeekableMemoryStream(responseContent);
            }
            setupRequest?.Invoke(mockResponse);

            MockTransport mockTransport = CreateMockTransport(mockResponse);
            var           pipeline      = new HttpPipeline(mockTransport, new[] { new LoggingPolicy(logContent: true, maxLength: maxLength) });

            using (Request request = pipeline.CreateRequest())
            {
                request.Method = RequestMethod.Get;
                request.Uri.Assign(new Uri("https://contoso.a.io"));

                Response response = await SendRequestAsync(pipeline, request);

                var buffer = new byte[11];

                if (IsAsync)
                {
                    Assert.AreEqual(6, await response.ContentStream.ReadAsync(buffer, 5, 6));
                    Assert.AreEqual(5, await response.ContentStream.ReadAsync(buffer, 6, 5));
                    Assert.AreEqual(0, await response.ContentStream.ReadAsync(buffer, 0, 5));
                }
                else
                {
                    Assert.AreEqual(6, response.ContentStream.Read(buffer, 5, 6));
                    Assert.AreEqual(5, response.ContentStream.Read(buffer, 6, 5));
                    Assert.AreEqual(0, response.ContentStream.Read(buffer, 0, 5));
                }

                return(mockResponse);
            }
        }
コード例 #13
0
        private async Task <Response> SendRequest(bool isSeekable, Action <MockResponse> setupRequest = null)
        {
            var mockResponse = new MockResponse(500);

            byte[] responseContent = Encoding.UTF8.GetBytes("Hello world");
            if (isSeekable)
            {
                mockResponse.ContentStream = new MemoryStream(responseContent);
            }
            else
            {
                mockResponse.ContentStream = new NonSeekableMemoryStream(responseContent);
            }
            setupRequest?.Invoke(mockResponse);

            var mockTransport = CreateMockTransport(mockResponse);
            var pipeline      = new HttpPipeline(mockTransport, new[] { LoggingPolicy.Shared });

            using (Request request = pipeline.CreateRequest())
            {
                request.SetRequestLine(HttpPipelineMethod.Get, new Uri("https://contoso.a.io"));

                Response response = await SendRequestAsync(pipeline, request, CancellationToken.None);

                var buffer = new byte[11];

                if (IsAsync)
                {
                    Assert.AreEqual(6, await response.ContentStream.ReadAsync(buffer, 5, 6));
                    Assert.AreEqual(5, await response.ContentStream.ReadAsync(buffer, 6, 5));
                    Assert.AreEqual(0, await response.ContentStream.ReadAsync(buffer, 0, 5));
                }
                else
                {
                    Assert.AreEqual(6, response.ContentStream.Read(buffer, 5, 6));
                    Assert.AreEqual(5, response.ContentStream.Read(buffer, 6, 5));
                    Assert.AreEqual(0, response.ContentStream.Read(buffer, 0, 5));
                }

                return(mockResponse);
            }
        }
コード例 #14
0
        public async Task RequestContentIsNotLoggedWhenDisabled()
        {
            var response = new MockResponse(500);

            response.ContentStream = new MemoryStream(new byte[] { 1, 2, 3 });

            MockTransport mockTransport = CreateMockTransport(response);

            var pipeline = new HttpPipeline(mockTransport, new[] { new LoggingPolicy(logContent: false) });

            using (Request request = pipeline.CreateRequest())
            {
                request.SetRequestLine(RequestMethod.Get, new Uri("https://contoso.a.io"));
                request.Content = HttpPipelineRequestContent.Create(Encoding.UTF8.GetBytes("Hello world"));

                await SendRequestAsync(pipeline, request);
            }

            AssertNoContentLogged();
        }
コード例 #15
0
        public static async Task <Request> ToPipelineRequestAsync(this HttpRequestMessage request, HttpPipeline pipeline)
        {
            Request pipelineRequest = pipeline.CreateRequest();

            pipelineRequest.Method = RequestMethod.Parse(request.Method.Method);

            pipelineRequest.Uri.Reset(request.RequestUri);

            pipelineRequest.Content = await request.Content.ToPipelineRequestContentAsync().ConfigureAwait(false);

            foreach (System.Collections.Generic.KeyValuePair <string, System.Collections.Generic.IEnumerable <string> > header in request.Headers)
            {
                foreach (var value in header.Value)
                {
                    pipelineRequest.Headers.Add(header.Key, value);
                }
            }

            return(pipelineRequest);
        }
コード例 #16
0
        public static async Task <Request> ToPipelineRequestAsync(this HttpRequestMessage request, HttpPipeline pipeline)
        {
            Request pipelineRequest = pipeline.CreateRequest();

            pipelineRequest.Method = RequestMethod.Parse(request.Method.Method);

            pipelineRequest.UriBuilder.Uri = request.RequestUri;

            pipelineRequest.Content = await request.Content.ToPipelineRequestContentAsync().ConfigureAwait(false);

            foreach (var header in request.Headers)
            {
                foreach (var value in header.Value)
                {
                    pipelineRequest.Headers.Add(header.Key, value);
                }
            }

            return(pipelineRequest);
        }
コード例 #17
0
        public async Task NonSeekableResponsesErrorsAreLoggedInBlocks()
        {
            var mockResponse = new MockResponse(500);

            mockResponse.ResponseContentStream = new NonSeekableMemoryStream(new byte[] { 6, 7, 8, 9, 0 });
            var mockTransport = new MockTransport(mockResponse);

            var    pipeline = new HttpPipeline(mockTransport, new [] { LoggingPolicy.Shared });
            string requestId;

            using (HttpPipelineRequest request = pipeline.CreateRequest())
            {
                request.SetRequestLine(HttpPipelineMethod.Get, new Uri("https://contoso.a.io"));
                requestId = request.RequestId;

                Response response = await pipeline.SendRequestAsync(request, CancellationToken.None);

                var buffer = new byte[10];
                Assert.AreEqual(3, await response.ContentStream.ReadAsync(buffer, 5, 3));
                Assert.AreEqual(2, await response.ContentStream.ReadAsync(buffer, 8, 2));
                Assert.AreEqual(0, await response.ContentStream.ReadAsync(buffer, 0, 5));
            }

            EventWrittenEventArgs[] errorContentEvents = _listener.EventsById(ErrorResponseContentBlockEvent).ToArray();

            Assert.AreEqual(2, errorContentEvents.Length);

            Assert.AreEqual(EventLevel.Informational, errorContentEvents[0].Level);
            Assert.AreEqual("ErrorResponseContentBlock", errorContentEvents[0].EventName);
            Assert.AreEqual(requestId, errorContentEvents[0].GetProperty <string>("requestId"));
            Assert.AreEqual(0, errorContentEvents[0].GetProperty <int>("blockNumber"));
            CollectionAssert.AreEqual(new byte[] { 6, 7, 8 }, errorContentEvents[0].GetProperty <byte[]>("content"));

            Assert.AreEqual(EventLevel.Informational, errorContentEvents[1].Level);
            Assert.AreEqual("ErrorResponseContentBlock", errorContentEvents[1].EventName);
            Assert.AreEqual(requestId, errorContentEvents[1].GetProperty <string>("requestId"));
            Assert.AreEqual(1, errorContentEvents[1].GetProperty <int>("blockNumber"));
            CollectionAssert.AreEqual(new byte[] { 9, 0 }, errorContentEvents[1].GetProperty <byte[]>("content"));

            CollectionAssert.IsEmpty(_listener.EventsById(ErrorResponseContentEvent));
        }
コード例 #18
0
        public async Task <Response> SendAsync(object data)
        {
            byte[] dataBytes = JsonSerializer.SerializeToUtf8Bytes(data);
            string s         = JsonSerializer.Serialize(data);

            var request = _pipeline.CreateRequest();

            request.Uri.Reset(new Uri($"https://{_location}.{_ingestEndpointPrefix}{_resourceName}/metrics?api-version=2018-09-01-preview"));
            request.Method = RequestMethod.Post;
            request.Headers.SetValue("Content-Type", "application/json");
            request.Content = RequestContent.Create(dataBytes);

            var response = await _pipeline.SendRequestAsync(request, default);

            if (response.Status != 200)
            {
                throw await _clientDiagnostics.CreateRequestFailedExceptionAsync(response);
            }

            return(response);
        }
コード例 #19
0
        public async Task GettingErrorRequestProducesEvents()
        {
            var response = new MockResponse(500);

            response.SetContent(new byte[] { 6, 7, 8, 9, 0 });
            response.AddHeader(new HttpHeader("Custom-Response-Header", "Improved value"));

            MockTransport mockTransport = CreateMockTransport(response);

            var    pipeline = new HttpPipeline(mockTransport, new[] { new LoggingPolicy(logContent: true, int.MaxValue) });
            string requestId;

            using (Request request = pipeline.CreateRequest())
            {
                request.Method = RequestMethod.Get;
                request.Uri.Assign(new Uri("https://contoso.a.io"));
                request.Headers.Add("Date", "3/26/2019");
                request.Headers.Add("Custom-Header", "Value");
                request.Content = HttpPipelineRequestContent.Create(new byte[] { 1, 2, 3, 4, 5 });
                requestId       = request.ClientRequestId;

                await SendRequestAsync(pipeline, request);
            }

            EventWrittenEventArgs e = _listener.SingleEventById(ErrorResponseEvent);

            Assert.AreEqual(EventLevel.Error, e.Level);
            Assert.AreEqual("ErrorResponse", e.EventName);
            Assert.AreEqual(requestId, e.GetProperty <string>("requestId"));
            Assert.AreEqual(e.GetProperty <int>("status"), 500);
            StringAssert.Contains($"Custom-Response-Header:Improved value{Environment.NewLine}", e.GetProperty <string>("headers"));

            e = _listener.SingleEventById(ErrorResponseContentEvent);
            Assert.AreEqual(EventLevel.Informational, e.Level);
            Assert.AreEqual("ErrorResponseContent", e.EventName);
            Assert.AreEqual(requestId, e.GetProperty <string>("requestId"));
            CollectionAssert.AreEqual(new byte[] { 6, 7, 8, 9, 0 }, e.GetProperty <byte[]>("content"));
        }
コード例 #20
0
        public async Task HelloWorld()
        {
            var pipeline = new HttpPipeline(new HttpClientTransport());

            var request = pipeline.CreateRequest();

            var uri = new Uri(@"https://raw.githubusercontent.com/Azure/azure-sdk-for-net/master/README.md");

            request.SetRequestLine(RequestMethod.Get, uri);
            request.Headers.Add("Host", uri.Host);

            Response response = await pipeline.SendRequestAsync(request, cancellationToken : default).ConfigureAwait(false);

            if (response.Status == 200)
            {
                var    reader       = new StreamReader(response.ContentStream);
                string responseText = reader.ReadToEnd();
            }
            else
            {
                throw await response.CreateRequestFailedExceptionAsync();
            }
        }
コード例 #21
0
        private Request CreateClientSecretAuthRequest(string tenantId, string clientId, string clientSecret, string[] scopes)
        {
            Request request = _pipeline.CreateRequest();

            request.Method = HttpPipelineMethod.Post;

            request.UriBuilder.Uri = _options.AuthorityHost;

            request.UriBuilder.AppendPath(tenantId);

            request.UriBuilder.AppendPath("/oauth2/v2.0/token");

            ReadOnlyMemory <byte> content = Serialize(
                ("response_type", "token"),
                ("grant_type", "client_credentials"),
                ("client_id", clientId),
                ("client_secret", clientSecret),
                ("scopes", string.Join(" ", scopes)));

            request.Content = HttpPipelineRequestContent.Create(content);

            return(request);
        }
コード例 #22
0
        public async Task ContentIsNotLoggedAsTextWhenDisabled()
        {
            var response = new MockResponse(500);

            response.ContentStream = new MemoryStream(new byte[] { 1, 2, 3 });
            response.AddHeader(new HttpHeader("Content-Type", "text/json"));

            MockTransport mockTransport = CreateMockTransport(response);

            var pipeline = new HttpPipeline(mockTransport, new[] { new LoggingPolicy(logContent: false, int.MaxValue) });

            using (Request request = pipeline.CreateRequest())
            {
                request.Method = RequestMethod.Get;
                request.Uri.Assign(new Uri("https://contoso.a.io"));
                request.Content = HttpPipelineRequestContent.Create(Encoding.UTF8.GetBytes("Hello world"));
                request.Headers.Add("Content-Type", "text/json");

                await SendRequestAsync(pipeline, request);
            }

            AssertNoContentLogged();
        }
コード例 #23
0
        public async Task PerRetryPolicyObservesRedirect()
        {
            List <string> uris           = new List <string>();
            var           options        = GetOptions();
            var           perRetryPolicy = new CallbackPolicy(message => uris.Add(message.Request.Uri.ToString()));

            options.AddPolicy(perRetryPolicy, HttpPipelinePosition.PerRetry);
            HttpPipeline httpPipeline      = HttpPipelineBuilder.Build(options);
            Uri          testServerAddress = null;

            using TestServer testServer = new TestServer(
                      context =>
            {
                if (context.Request.Path.ToString().Contains("/redirected"))
                {
                    context.Response.StatusCode = 200;
                }
                else
                {
                    context.Response.StatusCode = 300;
                    context.Response.Headers.Add("Location", testServerAddress + "/redirected");
                }
                return(Task.CompletedTask);
            });

            testServerAddress = testServer.Address;

            using Request request = httpPipeline.CreateRequest();
            request.Method        = RequestMethod.Get;
            request.Uri.Reset(testServer.Address);

            using Response response = await ExecuteRequest(request, httpPipeline);

            Assert.AreEqual(response.Status, 200);
            Assert.AreEqual(2, uris.Count);
            Assert.AreEqual(1, uris.Count(u => u.Contains("/redirected")));
        }
コード例 #24
0
        private Request CreateAddRequest(ConfigurationSetting setting)
        {
            Argument.AssertNotNull(setting, nameof(setting));
            Argument.AssertNotNullOrEmpty(setting.Key, $"{nameof(setting)}.{nameof(setting.Key)}");

            Request request = _pipeline.CreateRequest();

            ReadOnlyMemory <byte> content = Serialize(setting);

            request.Method = RequestMethod.Put;

            BuildUriForKvRoute(request.Uri, setting);

            MatchConditions requestOptions = new MatchConditions();

            requestOptions.IfNoneMatch = ETag.All;
            ConditionalRequestOptionsExtensions.ApplyHeaders(request, requestOptions);

            request.Headers.Add(s_mediaTypeKeyValueApplicationHeader);
            request.Headers.Add(HttpHeader.Common.JsonContentType);
            request.Content = RequestContent.Create(content);

            return(request);
        }
コード例 #25
0
        public async Task SendingRequestProducesEvents()
        {
            var response = new MockResponse(500);

            response.SetContent(new byte[] { 6, 7, 8, 9, 0 });
            response.AddHeader(new HttpHeader("Custom-Response-Header", "Improved value"));

            var mockTransport = new MockTransport(response);

            var    pipeline = new HttpPipeline(mockTransport, new [] { LoggingPolicy.Shared });
            string requestId;

            using (HttpPipelineRequest request = pipeline.CreateRequest())
            {
                request.SetRequestLine(HttpPipelineMethod.Get, new Uri("https://contoso.a.io"));
                request.AddHeader("Date", "3/26/2019");
                request.AddHeader("Custom-Header", "Value");
                request.Content = HttpPipelineRequestContent.Create(new byte[] { 1, 2, 3, 4, 5 });
                requestId       = request.RequestId;

                await pipeline.SendRequestAsync(request, CancellationToken.None);
            }

            var e = _listener.SingleEventById(RequestEvent);

            Assert.AreEqual(EventLevel.Informational, e.Level);
            Assert.AreEqual("Request", e.EventName);
            Assert.AreEqual(requestId, e.GetProperty <string>("requestId"));
            Assert.AreEqual("https://contoso.a.io/", e.GetProperty <string>("uri"));
            Assert.AreEqual("GET", e.GetProperty <string>("method"));
            StringAssert.Contains($"Date:3/26/2019{Environment.NewLine}", e.GetProperty <string>("headers"));
            StringAssert.Contains($"Custom-Header:Value{Environment.NewLine}", e.GetProperty <string>("headers"));

            e = _listener.SingleEventById(RequestContentEvent);
            Assert.AreEqual(EventLevel.Verbose, e.Level);
            Assert.AreEqual("RequestContent", e.EventName);
            Assert.AreEqual(requestId, e.GetProperty <string>("requestId"));
            CollectionAssert.AreEqual(new byte[] { 1, 2, 3, 4, 5 }, e.GetProperty <byte[]>("content"));

            e = _listener.SingleEventById(ResponseEvent);
            Assert.AreEqual(EventLevel.Informational, e.Level);
            Assert.AreEqual("Response", e.EventName);
            Assert.AreEqual(requestId, e.GetProperty <string>("requestId"));
            Assert.AreEqual(e.GetProperty <int>("status"), 500);
            StringAssert.Contains($"Custom-Response-Header:Improved value{Environment.NewLine}", e.GetProperty <string>("headers"));

            e = _listener.SingleEventById(ResponseContentEvent);
            Assert.AreEqual(EventLevel.Verbose, e.Level);
            Assert.AreEqual("ResponseContent", e.EventName);
            Assert.AreEqual(requestId, e.GetProperty <string>("requestId"));
            CollectionAssert.AreEqual(new byte[] { 6, 7, 8, 9, 0 }, e.GetProperty <byte[]>("content"));

            e = _listener.SingleEventById(ErrorResponseEvent);
            Assert.AreEqual(EventLevel.Error, e.Level);
            Assert.AreEqual("ErrorResponse", e.EventName);
            Assert.AreEqual(requestId, e.GetProperty <string>("requestId"));
            Assert.AreEqual(e.GetProperty <int>("status"), 500);
            StringAssert.Contains($"Custom-Response-Header:Improved value{Environment.NewLine}", e.GetProperty <string>("headers"));

            e = _listener.SingleEventById(ErrorResponseContentEvent);
            Assert.AreEqual(EventLevel.Informational, e.Level);
            Assert.AreEqual("ErrorResponseContent", e.EventName);
            Assert.AreEqual(requestId, e.GetProperty <string>("requestId"));
            CollectionAssert.AreEqual(new byte[] { 6, 7, 8, 9, 0 }, e.GetProperty <byte[]>("content"));
        }
コード例 #26
0
        public async Task SendingRequestProducesEvents()
        {
            var handler = new MockHttpClientHandler(httpRequestMessage =>
            {
                var response     = new HttpResponseMessage((HttpStatusCode)500);
                response.Content = new ByteArrayContent(new byte[] { 6, 7, 8, 9, 0 });
                response.Headers.Add("Custom-Response-Header", "Improved value");
                return(Task.FromResult(response));
            });
            var    transport = new HttpClientTransport(new HttpClient(handler));
            var    pipeline  = new HttpPipeline(transport, new [] { LoggingPolicy.Shared });
            string requestId;

            using (var request = pipeline.CreateRequest())
            {
                request.SetRequestLine(HttpPipelineMethod.Get, new Uri("https://contoso.a.io"));
                request.AddHeader("Date", "3/26/2019");
                request.AddHeader("Custom-Header", "Value");
                request.Content = HttpPipelineRequestContent.Create(new byte[] { 1, 2, 3, 4, 5 });
                requestId       = request.RequestId;

                var response = await pipeline.SendRequestAsync(request, CancellationToken.None);

                Assert.AreEqual(500, response.Status);
            }

            var e = _listener.SingleEventById(1);

            Assert.AreEqual(EventLevel.Informational, e.Level);
            Assert.AreEqual("Request", e.EventName);
            Assert.AreEqual(requestId, e.GetProperty <string>("requestId"));
            Assert.AreEqual("https://contoso.a.io/", e.GetProperty <string>("uri"));
            Assert.AreEqual("GET", e.GetProperty <string>("method"));
            StringAssert.Contains($"Date:3/26/2019{Environment.NewLine}", e.GetProperty <string>("headers"));
            StringAssert.Contains($"Custom-Header:Value{Environment.NewLine}", e.GetProperty <string>("headers"));

            e = _listener.SingleEventById(2);
            Assert.AreEqual(EventLevel.Verbose, e.Level);
            Assert.AreEqual("RequestContent", e.EventName);
            Assert.AreEqual(requestId, e.GetProperty <string>("requestId"));
            CollectionAssert.AreEqual(new byte[] { 1, 2, 3, 4, 5 }, e.GetProperty <byte[]>("content"));

            e = _listener.SingleEventById(5);
            Assert.AreEqual(EventLevel.Informational, e.Level);
            Assert.AreEqual("Response", e.EventName);
            Assert.AreEqual(requestId, e.GetProperty <string>("requestId"));
            Assert.AreEqual(e.GetProperty <int>("status"), 500);
            StringAssert.Contains($"Custom-Response-Header:Improved value{Environment.NewLine}", e.GetProperty <string>("headers"));

            e = _listener.SingleEventById(6);
            Assert.AreEqual(EventLevel.Verbose, e.Level);
            Assert.AreEqual("ResponseContent", e.EventName);
            Assert.AreEqual(requestId, e.GetProperty <string>("requestId"));
            CollectionAssert.AreEqual(new byte[] { 6, 7, 8, 9, 0 }, e.GetProperty <byte[]>("content"));

            e = _listener.SingleEventById(8);
            Assert.AreEqual(EventLevel.Error, e.Level);
            Assert.AreEqual("ErrorResponse", e.EventName);
            Assert.AreEqual(requestId, e.GetProperty <string>("requestId"));
            Assert.AreEqual(e.GetProperty <int>("status"), 500);
            StringAssert.Contains($"Custom-Response-Header:Improved value{Environment.NewLine}", e.GetProperty <string>("headers"));

            e = _listener.SingleEventById(9);
            Assert.AreEqual(EventLevel.Informational, e.Level);
            Assert.AreEqual("ErrorResponseContent", e.EventName);
            Assert.AreEqual(requestId, e.GetProperty <string>("requestId"));
            CollectionAssert.AreEqual(new byte[] { 6, 7, 8, 9, 0 }, e.GetProperty <byte[]>("content"));
        }