TypedResults
Transitioning to TypedResults in .NET Minimal APIs
We have been able to get some basics of how minimal APIs work. Now we would like to write clean, readable, and testable code in minimal APIs.
In the previous codebase, we used Results.Ok()
, Results.Created()
, Results.NotFound()
, etc. directly inside the lambda functions. We would like to refactor our code by:
Moving the logic to named static methods (making the code easier to test and reuse)
Using
TypedResults
, which provides a more explicit and strongly-typed way of returning responses
What is TypedResults?
TypedResults
is a class provided by .NET 7+ that offers type-safe versions of the response helper methods like:
TypedResults.Ok(...)
TypedResults.Created(...)
TypedResults.NotFound()
TypedResults.NoContent()
Benefits of TypedResults
It helps improve:
Readability: The intent of the method is clearer
Tooling support: IntelliSense and refactoring tools work better
Testing: You can test against expected return types
Implementation
Update the Program.cs code to the following:
Comparing Before and After
Feature | Old Code (Lambda) | New Code (TypedResults) |
---|---|---|
Return type |
|
|
Handler format | Inline lambdas | Separate static methods |
Reusability | Hard to reuse handlers | Easy to reuse/test individual methods |
Type safety | Less explicit return types | Strongly-typed result interface ( |
Key Improvements
Separation of Concerns: Each operation is now in its own method, making the code more organized
Testability: Static methods can be easily unit tested
Readability: The Program.cs file is cleaner and easier to understand
Maintainability: Changes to individual operations don't affect the routing setup
Type Safety: TypedResults provides better compile-time checking
Why Use Static Methods?
Static methods for API handlers provide several benefits:
No instance required: They can be called without creating an object
Performance: Slightly better performance as no instance allocation is needed
Testing: Easier to unit test as they don't depend on class state
Clarity: The method signature clearly shows what dependencies are needed
This approach makes your minimal API code more maintainable and follows .NET best practices for organizing API endpoints.