Understand controller
ASP.NET Core Web API Controllers
Here's the code for the entire WeatherController
class. Don't worry if it doesn't make sense yet. We'll go through it step by step.
The base class: ControllerBase
ControllerBase
A controller is a public class with one or more public methods known as actions.
By convention, a controller is placed in the project root's Controllers directory.
The actions are exposed as HTTP endpoints via routing.
So an HTTP
GET
request tohttps://localhost:{PORT}/weatherforecast
causes theGet()
method of theWeatherForecastController
class to be executed.The first thing to notice is that this class inherits from the
ControllerBase
base class. This base class provides a lot of standard functionality for handling HTTP requests, so you can focus on the specific business logic for your application.
If you have experience with Razor Pages or model-view-controller (MVC) architecture development in ASP.NET Core, you've used the Controller
class.
Don't create a web API controller by deriving from the Controller
class. Controller
derives from ControllerBase
and adds support for views, so it's for handling webpages, not web API requests.
API controller class attributes
Two important attributes are applied to WeatherForecastController
, as shown in the following code:
[ApiController]
enables features that make it easier to build web APIs.
[Route]
defines the routing pattern [controller]
. The [controller]
token is replaced by the controller's name (case-insensitive, without the Controller suffix).
This controller handles requests to https://localhost:{PORT}/weatherforecast
.
The route might contain static strings, as in api/[controller]
. If so, this controller would then handle a request to https://localhost:{PORT}/api/weatherforecast
.
Try these
What happens if you replace the route as given below
What happens if you remove the
[HttpGet(Name = "GetWeatherForecast")]
attribute just above the action method?
Last updated