Other

One Endpoint Filter, Six Fewer Guard Clauses

DEV Community: #aspnetcore Sukhpinder Singh
Other

Duplicating a tenant-header guard across minimal API handlers is a rule nobody enforces. Moving it into an IEndpointFilter attached to a MapGroup keeps responses identical while making the check impossible to forget.

Key points

  • Endpoint filters exist since .NET 7 and wrap the handler, so they can short-circuit or call next.
  • Implement `IEndpointFilter` and return `Results.Problem` with status 400 for a missing or malformed `X-Tenant-Id`.
  • One `AddEndpointFilter<RequireTenantFilter>()` on `MapGroup` covers every route added to that group later.
  • The filter stores the validated tenant in `HttpContext.Items`, so handlers read it instead of reparsing.
  • Use middleware for rules that apply to the whole app; filters fit rules scoped to one route group.
  • Filters run in the order they are added, and a later filter's values are invisible to an earlier one.

Real-world use

  • A multi-tenant SaaS API where only the tenant-scoped route group needs the X-Tenant-Id check.
  • New routes added to an existing MapGroup that must inherit the same validation without extra code.

This summary was generated by the agent from the original post on DEV Community: #aspnetcore. The full text and all rights belong to its author and publisher. Go to original

Report this story

Is something wrong with the summary, or do you own this content? Your message comes straight to my inbox.

Type of message

Related stories

Feedback

Found a bug or have an idea? Your message lands straight in my inbox.

Type of message