当前位置: 首页>>代码示例>>C#>>正文


C# HttpRequestMessage.GetCorrelationId方法代码示例

本文整理汇总了C#中System.Net.Http.HttpRequestMessage.GetCorrelationId方法的典型用法代码示例。如果您正苦于以下问题:C# HttpRequestMessage.GetCorrelationId方法的具体用法?C# HttpRequestMessage.GetCorrelationId怎么用?C# HttpRequestMessage.GetCorrelationId使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在System.Net.Http.HttpRequestMessage的用法示例。


在下文中一共展示了HttpRequestMessage.GetCorrelationId方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。

示例1: LogRequest

        private async void LogRequest(HttpRequestMessage request)
        {
            _log.InfoFormat("REQUEST {0} - {1}, {2}", request.GetCorrelationId(), request.Method, request.RequestUri);

            if (request.Content != null && _log.IsDebugEnabled)
            {
                var result = await request.Content.ReadAsByteArrayAsync();
                var content = Encoding.UTF8.GetString(result);

                _log.DebugFormat("REQUEST {0} - {1}", request.GetCorrelationId(), String.IsNullOrEmpty(content) ? "NO DATA SENT" : content);
            }
        }
开发者ID:asanjeevak,项目名称:Windays2015,代码行数:12,代码来源:MessageLogHandler.cs

示例2: GetCorrelationId_Returns_Valid_Guid

        public void GetCorrelationId_Returns_Valid_Guid()
        {
            // Arrange
            HttpRequestMessage request = new HttpRequestMessage();

            // Act
            Guid guid1 = request.GetCorrelationId();
            Guid guid2 = request.GetCorrelationId();

            // Assert
            Assert.Equal(guid1, guid2);
            Assert.NotEqual(guid1, Guid.Empty);
        }
开发者ID:huangw-t,项目名称:aspnetwebstack,代码行数:13,代码来源:HttpRequestMessageExtensionsTest.cs

示例3: DetermineCorrelationId

        private void DetermineCorrelationId(HttpRequestMessage request)
        {
            if (request != null)
            {
                // Ensure we have a correlation id on the request context / use Web API's MS_RequestId header
                var correlationId = request.GetCorrelationId();

                // Does the client override things?
                if (request.Headers.Contains(CorrelationIdHttpHeaderName))
                {
                    var temp = request.Headers
                        .GetValues(CorrelationIdHttpHeaderName)
                        .FirstOrDefault(s => s != null);
                    if (Guid.TryParse(temp, out correlationId))
                    {
                        // Overwrite the correlation id from Web API's MS_RequestId header
                        if (request.Properties.ContainsKey(HttpPropertyKeys.RequestCorrelationKey))
                        {
                            request.Properties.Remove(HttpPropertyKeys.RequestCorrelationKey);
                        }

                        request.Properties.Add(HttpPropertyKeys.RequestCorrelationKey, correlationId);
                    }
                }

                // Set the correlation id on the logical call context so HttpClients using
                // the CorrelatingHttpClientHandler can pass it along.
                CallContext.LogicalSetData(CallContextKey, correlationId);
            }
        }
开发者ID:ZhiYuanHuang,项目名称:NuGetGallery,代码行数:30,代码来源:WebApiCorrelationHandler.cs

示例4: SendAsync

        /// <summary>
        /// Event begin raised by the framework
        /// </summary>
        /// <param name="request">Current request</param>
        /// <param name="cancellationToken">Token to cancel async requests</param>
        /// <returns></returns>
        protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
        {
            IEnumerable<string> ids;
            request.Headers.TryGetValues("X-Correlation-Id", out ids);
            var enumerable = ids != null ? ids as IList<string> ?? ids.ToList() : null;
            var correlationId = enumerable != null && enumerable.Any() ? enumerable.FirstOrDefault() : request.GetCorrelationId().ToString();
            var requestMethod = request.Method.ToString();
            var requestUri = request.RequestUri.ToString();
            var startTime = DateTime.UtcNow;

            var requestMessage = await request.Content.ReadAsByteArrayAsync();

            IncomingRequest(correlationId, requestMethod, requestUri, requestMessage, request.Headers);

            var response = await base.SendAsync(request, cancellationToken);

            byte[] responseMessage;

            if (response.IsSuccessStatusCode && response.Content != null)
                responseMessage = await response.Content.ReadAsByteArrayAsync();
            else
                responseMessage = Encoding.UTF8.GetBytes(response.ReasonPhrase);

            var processingTime = (long)(DateTime.UtcNow - startTime).TotalMilliseconds;
            OutgoingRequest(correlationId, requestMethod, requestUri, responseMessage, response.Headers, processingTime);

            return response;
        }
开发者ID:WIBORI,项目名称:api-template,代码行数:34,代码来源:CorrelationHandler.cs

示例5: TraceRecord

 public TraceRecord(HttpRequestMessage request, string category, TraceLevel level)
 {
     Timestamp = DateTime.UtcNow;
     Request = request;
     RequestId = request != null ? request.GetCorrelationId() : Guid.Empty;
     Category = category;
     Level = level;
 }
开发者ID:marojeri,项目名称:aspnetwebstack,代码行数:8,代码来源:TraceRecord.cs

示例6: HandleRequest

        public override Task<Guid> HandleRequest(HttpRequestMessage request)
        {
            var correlationId = request.GetCorrelationId();

            _logger.Info($"ID: {correlationId} | {request.Method}: [{request.RequestUri}]");

            return Task.FromResult(correlationId);
        }
开发者ID:wongatech,项目名称:HealthMonitoring,代码行数:8,代码来源:MessageLoggingHandler.cs

示例7: SendAsync

        protected async override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) {

            Trace.TraceInformation(
                "Request Uri: {1}{0}HTTP Method: {2}{0}CorrelationId: {3}",
                Environment.NewLine,
                request.RequestUri.PathAndQuery,
                request.Method,
                request.GetCorrelationId()
            );

            return await base.SendAsync(request, cancellationToken);
        }
开发者ID:tugberkugurlu,项目名称:ProWebAPI.Samples,代码行数:12,代码来源:LoggerHandler.cs

示例8: SendAsync

        protected async override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
        {
            var reqId = request.GetCorrelationId().ToString();
            if (Global.Storage.TryAdd(reqId, request))
            {
                var result = await base.SendAsync(request, cancellationToken);

                object req;
                Global.Storage.TryRemove(reqId, out req);
                return result;
            }

            return await base.SendAsync(request, cancellationToken);
        }
开发者ID:diouf,项目名称:apress-recipes-webapi,代码行数:14,代码来源:MyHandler.cs

示例9: SetResponseCorrelationId

        private void SetResponseCorrelationId(HttpRequestMessage request, HttpResponseMessage response)
        {
            if (response != null)
            {
                // Do not allow overriding the header - if any code wants to set the correlation id
                // it shoud set the request property instead.
                if (response.Headers.Contains(CorrelationIdHttpHeaderName))
                {
                    response.Headers.Remove(CorrelationIdHttpHeaderName);
                }

                // Set correlation id header on the response
                response.Headers.Add(CorrelationIdHttpHeaderName, request.GetCorrelationId().ToString("D"));
            }
        }
开发者ID:ZhiYuanHuang,项目名称:NuGetGallery,代码行数:15,代码来源:WebApiCorrelationHandler.cs

示例10: LogRequest

        public void LogRequest(HttpRequestMessage request)
        {
            var dirPath = GetDirectoryPath("Requests");
            var fileName = DateTime.Now.ToString("yyyyMMdd_HHmmssffffff'.log'");
            var filePath = Path.Combine(dirPath, fileName);

            fileMap[request.GetCorrelationId()] = filePath;

            StringBuilder msg = new StringBuilder(1024);
            msg.AppendLine("[Request]");
            msg.AppendLine(string.Format("{0} {1} HTTP/{2}", request.Method, request.RequestUri.PathAndQuery, request.Version));
            foreach (var header in request.Headers)
            {
                msg.AppendFormat("{0}: ", header.Key);
                foreach (var value in header.Value)
                {
                    msg.AppendFormat("{0};", value);
                }
                msg.AppendLine();
            }

            if (request.Content != null)
            {
                var content = request.Content.ReadAsStringAsync().Result;
                if (!string.IsNullOrEmpty(content))
                {
                    msg.AppendLine();
                    msg.AppendLine(content);
                }
            }

            Trace.WriteLine(msg);

            using (var writer = new StreamWriter(filePath))
            {
                writer.WriteLine(msg.ToString());
            }
        }
开发者ID:jacktsai,项目名称:WebApiSurvey,代码行数:38,代码来源:FileRepository.cs

示例11: LogResponse

        public void LogResponse(HttpRequestMessage request, HttpResponseMessage response)
        {
            StringBuilder msg = new StringBuilder(1024);
            msg.AppendLine("[Response]");
            foreach (var header in response.Headers)
            {
                msg.AppendFormat("{0}: ", header.Key);
                foreach (var value in header.Value)
                {
                    msg.AppendFormat("{0};", value);
                }
                msg.AppendLine();
            }

            if (response.Content != null)
            {
                var content = response.Content.ReadAsStringAsync().Result;
                if (!string.IsNullOrEmpty(content))
                {
                    msg.AppendLine();
                    msg.AppendLine(content);
                }
            }

            Trace.WriteLine(msg);

            var filePath = fileMap[request.GetCorrelationId()];
            using (var writer = new StreamWriter(filePath, true))
            {
                writer.WriteLine(msg.ToString());
            }
        }
开发者ID:jacktsai,项目名称:WebApiSurvey,代码行数:32,代码来源:FileRepository.cs

示例12: SendAsync

        /// <summary>
        /// Sends an HTTP request to the inner handler to send to the server as an asynchronous operation.
        /// </summary>
        /// <param name="request">The HTTP request message to send to the server.</param>
        /// <param name="cancellationToken">A cancellation token to cancel operation.</param>
        /// <returns>Returns <see cref="T:System.Threading.Tasks.Task`1" />. The task object representing the asynchronous operation.</returns>
        protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
        {
            SetExecutionContextId(request.GetCorrelationId());

            return base.SendAsync(request, cancellationToken);
        }
开发者ID:chihoyeung,项目名称:NContext,代码行数:12,代码来源:ExecutionContextMessageHandler.cs

示例13: HandleRequest_should_log_request

        public async Task HandleRequest_should_log_request()
        {
            var request = new HttpRequestMessage
            {
                Method = HttpMethod.Put,
                RequestUri = new Uri("http://localhost/abc?def")
            };

            var correlationId = await _handler.HandleRequest(request);
            _logger.Verify(l => l.Info($"ID: {request.GetCorrelationId()} | {request.Method}: [{request.RequestUri}]"));

            Assert.Equal(request.GetCorrelationId(), correlationId);
        }
开发者ID:wongatech,项目名称:HealthMonitoring,代码行数:13,代码来源:MessageLoggingHandlerTests.cs

示例14: Format_Verbose_Builds_Trace_With_All_TraceRecord_Properties

        public void Format_Verbose_Builds_Trace_With_All_TraceRecord_Properties(TraceLevel level)
        {
            // Arrange
            HttpRequestMessage request = new HttpRequestMessage
            {
                RequestUri = new Uri("http://localhost"),
                Method = HttpMethod.Get
            };

            InvalidOperationException exception;
            try
            {
                // Want the full stack trace in the payload
                throw new InvalidOperationException("TestException");
            }
            catch (InvalidOperationException ex)
            {
                exception = ex;
            }

            TraceRecord traceRecord = new TraceRecord(request, "TestCategory", level)
            {
                Message = "TestMessage",
                Operation = "TestOperation",
                Operator = "TestOperator",
                Status = HttpStatusCode.Accepted,
                Exception = exception
            };

            // Act
            string formattedTrace = new SystemDiagnosticsTraceWriter() { IsVerbose = true }.Format(traceRecord);

            // Assert
            AssertContainsExactly(formattedTrace,
                                new Dictionary<string, string>
                                    {
                                        { "Level", level.ToString() },
                                        { "Kind", TraceKind.Trace.ToString() },
                                        { "Category", "'TestCategory'"},
                                        { "Id", request.GetCorrelationId().ToString() },
                                        { "Message", "'TestMessage'" },
                                        { "Operation", "TestOperator.TestOperation" },
                                        { "Status", "202 (Accepted)" },
                                        { "Exception", exception.ToString() },
                                    });

        }
开发者ID:KevMoore,项目名称:aspnetwebstack,代码行数:47,代码来源:SystemDiagnosticsTraceWriterTest.cs

示例15: Trace_Verbose_Writes_Correct_Message_To_TraceListeners_With_Only_Required_Fields_Set

        public void Trace_Verbose_Writes_Correct_Message_To_TraceListeners_With_Only_Required_Fields_Set()
        {
            // Arrange
            SystemDiagnosticsTraceWriter writer = CreateTraceWriter();
            writer.IsVerbose = true;

            HttpRequestMessage request = new HttpRequestMessage
            {
                RequestUri = new Uri("http://localhost"),
                Method = HttpMethod.Get
            };

            InvalidOperationException exception = new InvalidOperationException("TestException");

            // Act
            writer.Info(request, "TestCategory", String.Empty);

            // Assert
            string expected = String.Format("Level=Info, Kind=Trace, Category='TestCategory', Id={0}",
                                            request.GetCorrelationId().ToString());

            string actual = ((TestTraceListener)writer.TraceSource.Listeners[0]).Messages[0].Trim();
            string timePrefix = "] ";
            actual = actual.Substring(actual.IndexOf(timePrefix) + timePrefix.Length);
            Assert.Equal(expected, actual);
        }
开发者ID:KevMoore,项目名称:aspnetwebstack,代码行数:26,代码来源:SystemDiagnosticsTraceWriterTest.cs


注:本文中的System.Net.Http.HttpRequestMessage.GetCorrelationId方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。