How do you write custom middleware or an endpoint filter that reads endpoint metadata to conditionally alter its behavior per-route?
Short answer
Custom middleware calls context.GetEndpoint()?.Metadata.GetMetadata () to check for a specific metadata type attached to the matched endpoint, letting one piece of middleware behave differently for different routes based on declarative metadata rather than hardcoded route-path…
Advertisement
AModel answer
Custom middleware calls context.GetEndpoint()?.Metadata.GetMetadata<T>() to check for a specific metadata type attached to the matched endpoint, letting one piece of middleware behave differently for different routes based on declarative metadata rather than hardcoded route-path string comparisons, which is fragile and doesn't survive route template changes.
public record RateLimitOverrideAttribute(int MaxRequests);
app.MapGet("/api/expensive-report", GetReport)
.WithMetadata(new RateLimitOverrideAttribute(MaxRequests: 5));
// Custom middleware reads this metadata to apply a stricter limit just for this route
app.Use(async (context, next) => {
var override_ = context.GetEndpoint()?.Metadata.GetMetadata<RateLimitOverrideAttribute>();
var limit = override_?.MaxRequests ?? DefaultLimit;
// apply 'limit' for this specific request
await next();
});Real-world example
A rate-limiting middleware applies a much stricter request limit specifically to an expensive reporting endpoint by reading a custom RateLimitOverrideAttribute attached as endpoint metadata, rather than hardcoding a special case for that route's URL string.
Likely follow-ups
- Why is metadata-based route identification more maintainable than string-comparing request paths?
- How would you combine metadata from multiple attributes attached to the same endpoint?
Related topics