private async Task LogError(HttpContext context, Exception ex) { string bodyPart; using (var ms = new MemoryStream()) { bodyPart = await StreamHelpers.GetStreamPart(ms, 1024); } await _log.WriteErrorAsync("GlobalHandler", context.Request.GetUri().AbsoluteUri, bodyPart, ex); }
private async Task LogValidationError(HttpContext context, Exception ex) { string bodyPart; using (var memoryStream = new MemoryStream()) { bodyPart = await StreamHelpers.GetStreamPart(memoryStream, 1024); } await _log.WriteInfoAsync("GlobalHandler", context.Request.GetUri().AbsoluteUri, bodyPart + ex.Message); }
public async Task Invoke(HttpContext context) { var requestContext = $"Request path: {context?.Request?.Path}, {Environment.NewLine}Method: {context?.Request?.Method}"; try { if (_settings.Enabled && context.Request.Method.ToUpper() != "GET") { var reqBodyStream = new MemoryStream(); var originalRequestBody = new MemoryStream(); await context.Request.Body.CopyToAsync(reqBodyStream); reqBodyStream.Seek(0, SeekOrigin.Begin); await reqBodyStream.CopyToAsync(originalRequestBody); reqBodyStream.Seek(0, SeekOrigin.Begin); context.Request.Body = reqBodyStream; using (originalRequestBody) { var body = await StreamHelpers.GetStreamPart(originalRequestBody, _settings.MaxPartSize); var headers = context.Request.Headers.Where(h => !_personalDataHeaders.Contains(h.Key)).ToJson(); var userId = context.User.FindFirst(ClaimTypes.NameIdentifier)?.Value; var info = $"UserId:{userId} {Environment.NewLine}Body:{body} {Environment.NewLine}Headers:{headers}"; if (info.Length > MaxStorageFieldLength) { info = info.Substring(0, MaxStorageFieldLength); } await _requestsLog.WriteInfoAsync("MIDDLEWARE", "RequestsLoggingMiddleware", requestContext, info); } } } catch (Exception ex) { await _log.WriteErrorAsync("MIDDLEWARE", "RequestsLoggingMiddleware", requestContext, ex); } finally { await _next.Invoke(context); } }