you can use HttpContext object to access endpoint and metadata like attributes.
var endpoint = context.GetEndpoint();
var IsAllowAnonymous = endpointisAllowAnonymous != null && endpoint?.Metadata.Any(x=>xx => x.GetType()==typeof == typeof(AllowAnonymousAttribute));
then add a conditional in your check to skip.
if (isAllowAnonymous == true)
{
await _next(context);
return;
}
Note: you should place your middleware after Routing middleware to use GetEndpoint extension method. if your middleware place before Routing middleware
GetEndpoint extension method return null
app.UseRouting();
app.UseMiddleware<ApiKeyMiddleware>();