Skip to content

Instantly share code, notes, and snippets.

@stevetalkscode
Created February 6, 2021 11:12
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save stevetalkscode/caf976b73059f6095e6ca4c5d7f772be to your computer and use it in GitHub Desktop.
Save stevetalkscode/caf976b73059f6095e6ca4c5d7f772be to your computer and use it in GitHub Desktop.
public class LogUserAgentMiddleware : IMiddleware
{
private readonly ILogger _logger;
public LogUserAgentMiddleware(ILogger<LogUserAgentMiddleware> logger)
{
// The null check here is belt and braces in case there is a
// custom middleware factory that uses GetService instead of
// GetRequiredService. If using the default, this check is not
// required.
_logger = logger ?? throw new ArgumentNullException(nameof(logger));
}
public async Task InvokeAsync(HttpContext context, RequestDelegate next)
{
var userAgent = context.Request.Headers.GetCommaSeparatedValues("User-Agent").LastOrDefault();
if (userAgent is not null) _logger?.LogTrace($"User Agent : {userAgent}");
await next(context);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment