Web APIs
Web APIs use the MVC framework of ASP.NET Core.
The default Program.cs
looks like this:
A controller example:
The ControllerBase
has a bunch of useful methods, like the ones that return
different kinds of IActionResult
.
The ApiController
attribute applies some useful conventions to the controller
(e.g. the usage of ProblemDetails).
Routing
We can use exactly the same templates as in the Razor Pages
routing.
However, we speify those in a different place - in the action’s Route
attribute.
We can define multiple Route
s per action. We can define Route
on the
controller and the actions. In such a case, the action’s URL is a combination of
these two. We can sign out of that by prefixing action’s Route
with a /
.
Then, the action’s Route
is the URL.
HTTP Verb
Oura actions may also be marked with HTTP method to be used. We do that with attributes:
HttpPost
HttpGet
HttpPut
HttpDelete
- etc.
ApiController attribute
The following features are introduced with the ApiController
attribute:
- complex action parameters are assumed to be
FromBody
and we don’t need to use that attribute. By default, form would be expected. - the
ModelState.IsValid
is executed automatically (via a filter) and 400 is returned in case it fails. - The error status code are automatically converte to the ProblemDetails convention.
Returning data
We can return data from actions directly (e.g. return new ["a", "b", "c"]
) or
we can return some IActionResult
. In the first case it would be the same as
returning an OkResult
with the Ok()
helper.
Formats
By default, ASP.NET Core returns data in JSON format. We can change that by
adding additional providers. For example, to add text/xml
support: