public async Task Invoke(HttpContext context) { var request = context.Request; var requestId = ( request.Headers.TryGetValue(HttpHeaderConstants.HTTP_HEADER_REQUEST_ID, out var requestIdValue) && requestIdValue.Count != 0 && Guid.TryParse(requestIdValue[0], out var requestIdFromHeader) ) ? requestIdFromHeader : GuiDate.GenerateTimeBasedGuid(); var correlationId = ( request.Headers.TryGetValue(HttpHeaderConstants.HTTP_HEADER_CORRELATION_ID, out var correlationIdValue) && correlationIdValue.Count != 0 && Guid.TryParse(correlationIdValue[0], out var correlationIdFromHeader) ) ? correlationIdFromHeader : requestId; request.HttpContext.Items[HttpHeaderConstants.HTTP_HEADER_REQUEST_ID] = requestId; request.HttpContext.Items[HttpHeaderConstants.HTTP_HEADER_CORRELATION_ID] = correlationId; var response = context.Response; response.Headers[HttpHeaderConstants.HTTP_HEADER_APP_NAME] = _applicationName; response.Headers[HttpHeaderConstants.HTTP_HEADER_REQUEST_ID] = $"{requestId}"; response.Headers[HttpHeaderConstants.HTTP_HEADER_CORRELATION_ID] = $"{correlationId}"; response.Headers[HttpHeaderConstants.HTTP_HEADER_CLIENT_IP_ADRESSS] = $"{request.HttpContext.Items[HttpHeaderConstants.HTTP_HEADER_CLIENT_IP_ADRESSS]}"; await _next(context); }
public Guid GetRequestIdFromRequest(HttpRequest request) { var errorMessage = $"{HttpHeaderConstants.HTTP_HEADER_REQUEST_ID} http request header is missing or not formatted correctly !"; Guid requestId; if (request.Headers.TryGetValue(HttpHeaderConstants.HTTP_HEADER_REQUEST_ID, out var values)) { var ids = values.ToArray(); if (ids.Length != 1 || !Guid.TryParse(ids[0], out requestId)) { throw new HttpRequestException(errorMessage); } } else { requestId = GuiDate.GenerateTimeBasedGuid(); request.Headers.Add(HttpHeaderConstants.HTTP_HEADER_REQUEST_ID, requestId.ToString()); } return(requestId); }