Skip to content

Instantly share code, notes, and snippets.

@tekguy
Last active March 23, 2020 21:30
Show Gist options
  • Save tekguy/52b245f6582158d7240f80bf46c4cc71 to your computer and use it in GitHub Desktop.
Save tekguy/52b245f6582158d7240f80bf46c4cc71 to your computer and use it in GitHub Desktop.
Middleware for ASP.NET Core 3.1 WebAPI project to log response content size to app insights
public class ApiLoggingMiddleware
{
private readonly RequestDelegate _next;
public ApiLoggingMiddleware(RequestDelegate next)
{
_next = next;
}
public async Task InvokeAsync(HttpContext context)
{
var originalBodyStream = context.Response.Body;
using (var responseBody = new MemoryStream())
{
context.Response.Body = responseBody;
await _next(context);
// get app insights request telemetry for sdk
var requestTelemetry = context.Features.Get<RequestTelemetry>();
if (requestTelemetry != null)
{
// get the content size
var contentSize = GetContentSize(context.Response);
// append to the request telemetry
requestTelemetry.Metrics.Add(new KeyValuePair<string, double>("Size", contentSize));
}
await responseBody.CopyToAsync(originalBodyStream);
}
}
private long GetContentSize(HttpResponse response)
{
var size = response.Body.Length;
// reset
response.Body.Seek(0, SeekOrigin.Begin);
return size;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment