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.
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
.
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