ASP.NET Core¶
The package Fluent.Unions.AspNetCore (namespace Fluent.Unions.AspNetCore) turns results and options into HTTP responses, so an endpoint returns the outcome of an operation and the status code follows from it.
In this section¶
- HTTP results:
ToHttpResultfor each type, theTaskoverloads, and minimal API and controller usage. - Endpoint filter:
WithResultMappinglets handlers return results directly, on one endpoint or a whole route group. - Error mapping: which exception gives which status code, how to change it, and how
ProblemDetailsis written.
Quick example¶
using Fluent.Unions.AspNetCore;
app.MapGet("/orders/{id}", async (Guid id, IOrders orders) => await orders.LoadOrderAsync(id).ToHttpResult());
LoadOrderAsync returns a Task<Result<Order>>. The endpoint answers with the table below.
| Input | Response |
|---|---|
Result<T> or Option<T> with a value |
200 with the value as JSON |
Result that succeeded |
204 |
None |
404 with an empty body |
| error | ProblemDetails with the status code mapped from the exception type; validation errors as ValidationProblemDetails |
| Your own result type with a value | 200 with the value |
| Your own result type with a data error | the response you return from the onError callback |
When to use¶
- Your handlers already return
Result<T>orOption<T>, and you want one consistent way to turn them into responses. - You want errors as
ProblemDetailswithout writing atry/catchin every endpoint. - You model errors as data and want the compiler to check that each case has a response.
Rules¶
- Add the package, not just the library.
Fluent.Unions.AspNetCorereferencesFluent.Unions. It needs theMicrosoft.AspNetCore.Appframework. - Messages are hidden by default. The exception message becomes
detailonly for validation errors and for types you map withexposeMessage: true. - The filter handles every result type.
Result,Result<T>,Option<T>, and your own declared result type. An error that is not an exception gives 500 there, so useToHttpResult(onError)for it. See Endpoint filter. - Results are not JSON.
JsonSerializerrefusesResult<T>. Always convert before the response is written. - Errors as data need a mapping. A declared type with a record error has no default, so the compiler checks every case.
Back to index: Docs index ยท Next: HTTP results