Exploring responses
As with controller-based projects, with route handlers of minimal APIs as well, we can directly return a string or a class (either synchronously or asynchronously):
- If we return a string (as in the examples of the previous section), the framework writes the string directly to the response, setting its content type to
text/plain
and the status code to200 OK
- If we use a class, the object is serialized into the JSON format and sent to the response with the
application/json
content type and a200 OK
status code
However, in a real application, we typically need to control the response type and the status code. In this case, we can use the static Results
class, which allows us to return an instance of the IResult
interface, which in minimal APIs acts how IActionResult
does for controllers. For instance, we can use it to return a 201 Created
response rather than a 400 Bad Request
or a 404 Not Found
message. L et’s look at some examples:
app...