本文整理汇总了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);
}
}
示例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);
}
示例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);
}
}
示例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;
}
示例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;
}
示例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);
}
示例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);
}
示例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);
}
示例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"));
}
}
示例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());
}
}
示例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());
}
}
示例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);
}
示例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);
}
示例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() },
});
}
示例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);
}