using Microsoft.AspNetCore.Mvc;
using webapi.Services;
namespace webapi.Controllers
{
[Route("api/[controller]")]
public class CategoryController : ControllerBase
{
ICategoryService categoryServiceLocal;
public CategoryController(ICategoryService service)
{
categoryServiceLocal = service;
}
[HttpGet]
public IActionResult Get()
{
return Ok(categoryServiceLocal.Get());
}
}
}
- Using Directives:
using Microsoft.AspNetCore.Mvc;
using webapi.Services;
These are the using
directives at the beginning of the file.
They specify which namespaces the code will use. Microsoft.AspNetCore.Mvc
is required for working with ASP.NET Core MVC, and webapi.Services
that contains the ICategoryService
interface and other service-related code.
- Namespace and Class Declaration:
namespace webapi.Controllers
{
[Route("api/[controller]")]
public class CategoryController : ControllerBase
{
// ...
}
}
This code defines a C# namespace webapi.Controllers
and a class CategoryController
that belongs to this namespace.
The CategoryController
class inherits from ControllerBase
, which is a base class provided by ASP.NET Core for building controllers.
- Constructor:
ICategoryService categoryServiceLocal;
public CategoryController(ICategoryService service)
{
categoryServiceLocal = service;
}
This is the constructor of the CategoryController
class.
It takes an argument of type ICategoryService
(an interface for category-related services) and assigns it to the categoryServiceLocal
field.
This is a dependency injection, that allows to inject the ICategoryService
implementation into the controller.
- Route Attribute:
[Route("api/[controller]")]
This attribute specifies a route for the controller.
In this case, it defines a route template that includes [controller]
, which is a token that will be replaced with the name of the controller class, so requests to this controller will be mapped to routes like /api/Category
.
- HTTP GET Action:
[HttpGet]
public IActionResult Get()
{
return Ok(categoryServiceLocal.Get());
}
This is an HTTP GET action method that handles incoming GET requests to the route defined by the controller.
When a GET request is made to the route, this method is executed.
[HttpGet]
is an attribute that specifies that this method should respond to HTTP GET requests.public IActionResult Get()
is the method signature. It returns anIActionResult
, which is a generic result type that represents the result of an action.- Inside the method:
return Ok(categoryServiceLocal.Get());
returns an HTTP 200 OK response with the result of calling theGet
method on thecategoryServiceLocal
. - The
Get
method of the service returns the data that will be send as the response.
In summary, this code defines an ASP.NET Core Web API controller named CategoryController
with a single GET action that retrieves data from a category service and returns it as an HTTP response.
The route for this controller is /api/Category
, and it’s designed to work with dependency injection for the ICategoryService
.