What is endpoint metadata, and how do attributes like [Authorize] and custom metadata attach to a specific route for later inspection by middleware?
Short answer
Endpoint metadata is arbitrary data attached to a matched route (via attributes on controller actions, or .WithMetadata()/.RequireAuthorization() fluent calls on minimal API endpoints), stored in the Endpoint object that middleware running after UseRouting can inspect via…
Advertisement
AModel answer
Endpoint metadata is arbitrary data attached to a matched route (via attributes on controller actions, or .WithMetadata()/.RequireAuthorization() fluent calls on minimal API endpoints), stored in the Endpoint object that middleware running after UseRouting can inspect via HttpContext.GetEndpoint() -- this is precisely how UseAuthorization knows an endpoint requires authentication: it reads the [Authorize] attribute's metadata attached to the matched endpoint.
app.MapGet("/admin/reports", GetReports)
.RequireAuthorization()
.WithMetadata(new AuditLogAttribute("SensitiveDataAccess"));
// Custom middleware can inspect this metadata:
app.Use(async (context, next) => {
var endpoint = context.GetEndpoint();
var auditAttr = endpoint?.Metadata.GetMetadata<AuditLogAttribute>();
if (auditAttr != null) { /* log access */ }
await next();
});Real-world example
A custom auditing middleware inspects each matched endpoint's metadata for a custom AuditLogAttribute, automatically logging access to any endpoint tagged with it, without needing to hardcode a list of sensitive routes anywhere else in the codebase.
Likely follow-ups
- How does this metadata-based approach avoid tight coupling between middleware and specific routes?
- What built-in metadata types does ASP.NET Core itself attach to endpoints?
Related topics