In ASP.NET Core 10, what do WithMetadata, WithName and WithDisplayName attach to an endpoint, and how does custom middleware read that metadata?
answer
- Endpoint.Metadata is an ordered collection
- GetMetadata<T>() returns the last match
- WithName adds EndpointNameMetadata
- names are unique and case-sensitive
- DisplayName shows up in logs
basics
~10 sWithMetadata adds arbitrary objects to the endpoint's metadata; WithName adds an endpoint name used for link generation; WithDisplayName sets the label used in logs and errors. Middleware after routing calls GetEndpoint()?.Metadata.GetMetadata<T>() to read them.
solid answer
~40 sEvery endpoint has an immutable `Metadata` collection. Attributes on a Minimal API handler or controller action become metadata, and `.WithMetadata(...)` adds any object you like. `.WithName("GetOrder")` adds `EndpointNameMetadata` and `RouteNameMetadata`; names must be unique across the app (they are compared case-sensitively) and are what `LinkGenerator.GetPathByName` looks up. `.WithDisplayName("Get order")` changes `Endpoint.DisplayName`, the text in routing's "Request matched endpoint" and "Executing endpoint" log lines and in ambiguity errors; it does not affect matching. Middleware placed after routing reads metadata with `context.GetEndpoint()?.Metadata.GetMetadata<T>()`, which returns the most significant item, the last one added, so an action-level attribute overrides a controller-level one. That pattern is how authorization, CORS and output caching apply per-endpoint behaviour.
code
csharp · 19 linesvar app = WebApplication.CreateBuilder(args).Build();
app.MapGet("/orders/{id:int}", (int id) => Results.Ok(new { id }))
.WithName("GetOrder") // EndpointNameMetadata + RouteNameMetadata
.WithDisplayName("Orders: get one") // shown in routing logs
.WithMetadata(new RequiresOpenKitchenAttribute());
app.Use(async (context, next) =>
{
var endpoint = context.GetEndpoint();
var marker = endpoint?.Metadata.GetMetadata<RequiresOpenKitchenAttribute>();
app.Logger.LogInformation("{Endpoint} needs kitchen: {Needs}",
endpoint?.DisplayName, marker is not null);
await next(context);
});
app.Run();
public sealed class RequiresOpenKitchenAttribute : Attribute { }go deeper
Recall that endpoints carry metadata, that attributes become metadata, and that WithName names an endpoint for link generation.
Explain WithMetadata, WithName and WithDisplayName, and how middleware reads metadata with GetEndpoint() after routing.
Build metadata-driven middleware with correct placement and 'last wins' semantics, and keep endpoint names unique and display names useful for diagnosing production logs.
Standardise cross-cutting policy as endpoint metadata plus middleware, so features stay declarative and auditable instead of scattered across handlers.
## What endpoint metadata is An ASP.NET Core **endpoint** has a `RequestDelegate`, a `DisplayName`, and an `EndpointMetadataCollection` called `Metadata`. Metadata is an ordered, immutable list of arbitrary objects that describes the endpoint to the rest of the framework: HTTP methods, authorization requirements, CORS policies, names, OpenAPI descriptions and your own markers. Routing builds it once when endpoints are created; nothing changes it per request. Metadata comes from three places: 1. **Attributes** on the handler method or controller action and controller class. 2. **Conventions** chained on the builder: `.WithMetadata(...)`, `.RequireAuthorization()`, `.WithName(...)` and others. 3. **Group conventions** from `MapGroup`, which apply to every endpoint in the group. ## WithMetadata, WithName, WithDisplayName | Call | Adds | Used by | |---|---|---| | `.WithMetadata(params object[] items)` | the objects you pass | any middleware or feature that looks for that type | | `.WithName("GetOrder")` | `EndpointNameMetadata` and `RouteNameMetadata` | link generation by name; API description tools | | `.WithDisplayName("Get order")` | sets `Endpoint.DisplayName` | logs, diagnostics, ambiguity messages | Details that matter: - **Names are global.** If two endpoints share a name, routing throws an `InvalidOperationException` headed "The following endpoints with a duplicate endpoint name were found." Names are compared **case-sensitively** (ordinal). - **Display names are labels only.** Minimal API endpoints get a default such as `HTTP: GET /orders/{id}`, plus `=> GetOrder` when the handler is a named method; controller actions default to `Namespace.Controller.Action (Assembly)`. Changing the display name never changes matching. - **Metadata does not change matching by itself**, except for types a matcher policy reads, such as `HttpMethodMetadata` or host metadata from `RequireHost`. ## Reading metadata in middleware A food-delivery API wants to refuse order placement while the kitchen is closed, without repeating the check in every handler: ```csharp [AttributeUsage(AttributeTargets.Method | AttributeTargets.Class)] public sealed class RequiresOpenKitchenAttribute : Attribute { } app.MapPost("/orders", [RequiresOpenKitchen] (OrderRequest r) => Results.Accepted()); app.Use(async (context, next) => { var marker = context.GetEndpoint()?.Metadata.GetMetadata<RequiresOpenKitchenAttribute>(); if (marker is not null && !KitchenClock.IsOpen()) { context.Response.StatusCode = StatusCodes.Status503ServiceUnavailable; return; } await next(context); }); ``` The middleware must run **after routing has selected the endpoint**. In a `WebApplication` that does not call `UseRouting` explicitly, routing runs first, so `app.Use` is already in the right place. The collection offers three readers: - `GetMetadata<T>()` returns the **most significant** item of type `T`, which is the **last** one in the collection, or `null`. - `GetRequiredMetadata<T>()` does the same but throws if none exists. - `GetOrderedMetadata<T>()` returns all of them in order. Because later items are more significant, an attribute on an action overrides the same attribute on its controller, and a convention chained on the endpoint overrides one from its group. ## Built-in metadata you will meet When you dump `endpoint.Metadata` for a typical API endpoint you will see framework types next to your own: - `HttpMethodMetadata`, from `MapGet` or `[HttpGet]`, read by the HTTP-method matcher policy. - `AuthorizeAttribute` (an `IAuthorizeData`), from `[Authorize]` or `RequireAuthorization`, read by the authorization middleware. - `EndpointNameMetadata` and `RouteNameMetadata`, from `WithName`, read by link generation. - Host metadata from `RequireHost` or `[Host]`, read by the host matcher policy. - The handler's own `MethodInfo` for Minimal API endpoints, used by parameter binding and API description. ## Why this design Before endpoint routing, each feature that needed per-route behaviour had to integrate with MVC's filters or parse paths in terminal middleware. Metadata lets features like `UseAuthorization`, `UseCors`, rate limiting and output caching stay ordinary middleware while still applying a different policy per endpoint. Your own cross-cutting rules can use the same mechanism. ## What interviewers listen for - Metadata is immutable, built at startup, and comes from attributes and conventions. - `GetEndpoint()?.Metadata.GetMetadata<T>()` after routing, and "last wins". - `WithName` is for addressing (unique, case-sensitive); `WithDisplayName` is for humans. - The metadata-plus-middleware pattern is how built-in policies work.
- A controller has [RequiresOpenKitchen] at class level and an action also has it with different settings. Which one does GetMetadata<T>() return for that action?The action's. Metadata is ordered from least to most specific, controller attributes before action attributes, and `GetMetadata<T>()` returns the last item of the requested type. Use `GetOrderedMetadata<T>()` when you need every instance, for example to combine settings.
- What happens if two endpoints in the same app call WithName("GetOrder")?Routing's endpoint-name address scheme detects the duplicate and throws an `InvalidOperationException` listing the endpoints that share the name. Names are compared ordinally, so `GetOrder` and `getorder` are different names; even so, keep names unique regardless of case so they stay readable.
- Believes WithDisplayName changes the URL or how the endpoint is matched.
- Expects GetMetadata<T>() to return the first matching item rather than the last.
- Reads endpoint metadata in middleware placed before an explicit UseRouting call.
- Mutates endpoint metadata per request to pass data to the handler.
- Assumes endpoint names may repeat as long as the templates differ.