In ASP.NET Core Minimal APIs, how do you write a custom IResult that also describes its own response through IEndpointMetadataProvider?
answer
- Task ExecuteAsync(HttpContext)
- static PopulateMetadata(MethodInfo, EndpointBuilder)
- ProducesResponseTypeMetadata(status, type, contentTypes)
- IStatusCodeHttpResult, IValueHttpResult<T>
- IResultExtensions for discoverability
basics
~10 sImplement IResult.ExecuteAsync to write the status, headers and body, and IEndpointMetadataProvider's static PopulateMetadata to add a ProducesResponseTypeMetadata; the metadata is used only when the handler's declared return type is your type.
solid answer
~40 sA custom result is a class implementing `IResult`, whose `ExecuteAsync(HttpContext)` sets the status code, adds any headers and writes the body, for example with `httpContext.Response.WriteAsJsonAsync(value)`. To document itself, it also implements `IEndpointMetadataProvider` and its `static void PopulateMetadata(MethodInfo method, EndpointBuilder builder)`, adding `new ProducesResponseTypeMetadata(409, typeof(ReturnRefusal), ["application/json"])` to `builder.Metadata`. ASP.NET Core calls that method once, when the endpoint is built, and only if the handler's **declared** return type, or a type argument of its `Results<...>` union, is the custom type. Implementing `IStatusCodeHttpResult` and `IValueHttpResult<T>` lets filters and tests inspect it like a built-in result, and an extension method on `IResultExtensions` makes it callable as `TypedResults.Extensions.ReturnRefused(...)`.
code
csharp · 15 linespublic static class ReturnResults
{
public static ReturnRefused ReturnRefused(this IResultExtensions _, ReturnRefusal refusal) =>
new(refusal);
}
app.MapPost("/orders/{orderId}/items/{sku}/return",
async Task<Results<Ok<ReturnLabel>, ReturnRefused>> (
int orderId, string sku, IReturnsService returns) =>
{
var outcome = await returns.RequestAsync(orderId, sku);
return outcome.Refusal is { } r
? TypedResults.Extensions.ReturnRefused(r)
: TypedResults.Ok(outcome.Label!);
});go deeper
Know that any class implementing IResult with an ExecuteAsync method can be returned from a Minimal API handler.
Explain the ExecuteAsync and static PopulateMetadata split and why the declared return type decides whether metadata is used.
Package shared response shapes as custom results with metadata, status and value interfaces and IResultExtensions, and keep them AOT-friendly.
Decide which response shapes deserve a shared custom result across teams and how those types are versioned as part of the API contract.
## When a custom result is worth it The built-in results cover most needs, but an electronics retailer's returns API has one response it sends from many endpoints: a **refused return**. It is a 409 with a structured body (reason code, the policy window, the order date) and a `Link` header pointing at the returns policy. Rebuilding that from `TypedResults.Conflict(...)` plus header code in every handler invites drift. A custom `IResult` puts the shape in one place. ## The two contracts | Contract | Member | Called | |---|---|---| | `IResult` (`Microsoft.AspNetCore.Http`) | `Task ExecuteAsync(HttpContext httpContext)` | per request, after the handler returns | | `IEndpointMetadataProvider` (`Microsoft.AspNetCore.Http.Metadata`) | `static abstract void PopulateMetadata(MethodInfo method, EndpointBuilder builder)` | once, when the endpoint is built | ```csharp public sealed record ReturnRefusal(string Reason, int WindowDays, DateOnly OrderedOn); public sealed class ReturnRefused(ReturnRefusal refusal) : IResult, IEndpointMetadataProvider, IStatusCodeHttpResult, IValueHttpResult, IValueHttpResult<ReturnRefusal> { public int? StatusCode => StatusCodes.Status409Conflict; public ReturnRefusal? Value => refusal; object? IValueHttpResult.Value => refusal; public Task ExecuteAsync(HttpContext httpContext) { httpContext.Response.StatusCode = StatusCodes.Status409Conflict; httpContext.Response.Headers.Link = "</policies/returns>; rel=\"help\""; return httpContext.Response.WriteAsJsonAsync(refusal); } public static void PopulateMetadata(MethodInfo method, EndpointBuilder builder) => builder.Metadata.Add(new ProducesResponseTypeMetadata( StatusCodes.Status409Conflict, typeof(ReturnRefusal), ["application/json"])); } ``` ## When the metadata is actually read `PopulateMetadata` is static, so ASP.NET Core can only call it on a type it knows **before** any request runs: 1. The request delegate factory takes the handler's declared return type and unwraps `Task<T>` or `ValueTask<T>`. 2. If that type implements `IEndpointMetadataProvider`, its `PopulateMetadata` runs. 3. If that type is a `Results<...>` union, the union's own `PopulateMetadata` calls it on each type argument, so `Results<Ok<ReturnLabel>, ReturnRefused>` documents both 200 and 409. 4. A handler declared as `IResult` gets nothing, whatever it returns at run time. The interface is also honoured on **parameter types**: a handler parameter whose type implements `IEndpointMetadataProvider` contributes metadata the same way. ## Making it feel built in - **`IStatusCodeHttpResult`**, **`IValueHttpResult<T>`** and the non-generic **`IValueHttpResult`** are the interfaces the built-in results implement; the generic one does not extend the non-generic one, so implement both. Endpoint filters that log status codes and unit tests that check values work with your type without special cases. - **`IResultExtensions`**: both `Results.Extensions` and `TypedResults.Extensions` return an `IResultExtensions` instance that exists only to hang extension methods on. Add `public static ReturnRefused ReturnRefused(this IResultExtensions _, ReturnRefusal r) => new(r);` and handlers write `TypedResults.Extensions.ReturnRefused(refusal)`. - **Return a concrete type from the extension**, not `IResult`, or handlers that use it lose the metadata. ## Cheaper alternatives to check first | Need | Simpler option | What you give up | |---|---|---| | 409 with a JSON body | `TypedResults.Conflict(refusal)` | nothing; it documents itself | | any status with JSON | `TypedResults.Json(refusal, statusCode: 409)` | response metadata, since the status is dynamic | | an extra header on one endpoint | set it through an `HttpResponse` parameter and return `Conflict<T>` | reuse across endpoints | | the same shape everywhere | a custom `IResult` | a little more code | A custom result earns its place when the same combination of status, headers and body is repeated across many endpoints, or when the body is not JSON at all, such as a CSV export or an HTML fragment. ## Pitfalls - **Writing after the response started.** `ExecuteAsync` runs last; if a filter or middleware has already flushed headers, setting `StatusCode` throws. Keep custom results pure writers. - **JSON options.** `WriteAsJsonAsync` without options uses the app's configured HTTP JSON options, so casing matches the rest of the API. - **Native AOT.** A union's metadata is gathered by reflection when dynamic code is unavailable, and the source says a `PopulateMetadata` provided only by a default interface implementation is not supported there; declare it on the class. - **Over-engineering.** If the response is just a status and a body, `TypedResults.Conflict(refusal)` already documents itself. ## What interviewers listen for - The **split between run-time writing and build-time description**. - That metadata depends on the **declared** type. - The supporting interfaces and **`IResultExtensions`** as the idiomatic entry point.
- Why is PopulateMetadata static rather than an instance method?Endpoint metadata is assembled once, when the endpoint is built, before any request has produced a result object. A static abstract interface member lets ASP.NET Core call the method on the declared type without an instance. That is also why only the declared return type, not the runtime object, can contribute metadata.
- How does an endpoint filter recognise your custom result without knowing its type?Through the shared result interfaces. A filter can test `result is IStatusCodeHttpResult { StatusCode: 409 }` or `result is IValueHttpResult<ReturnRefusal> v` and read `v.Value`. Built-in results implement the same interfaces, so one filter handles both, and a `Results<...>` union is unwrapped through `INestedHttpResult.Result`.
- PopulateMetadata runs per request on the returned result instance.
- A custom result's metadata is picked up even when the handler is declared to return IResult.
- A custom Minimal API result should implement IActionResult.ExecuteResultAsync.
- Custom results must be registered in DI before handlers can return them.
- An IResultExtensions extension method should return IResult so it fits every handler.