Ticker

6/recent/ticker-posts

Web API Controllers

Web API Controllers

Introduction

Web API controllers are an essential component in developing web applications that provide a RESTful API. They are responsible for handling HTTP requests and generating appropriate responses. In this documentation, we will explore the basics of Web API controllers, including their structure, routing, and how to handle different types of HTTP requests.

Table of Contents

  1. Creating a Web API Controller
    • Example: Creating a Basic Web API Controller
    • Explanation: Understanding the Structure of a Web API Controller
  2. Routing in Web API Controllers
    • Example: Configuring Routes for Web API Controllers
    • Explanation: Mapping Routes to Controller Actions
  3. Handling HTTP Requests
    • Example: Handling GET Requests
    • Example: Handling POST Requests
    • Example: Handling PUT and DELETE Requests
    • Explanation: Processing Different Types of Requests
  4. Returning Responses
    • Example: Returning Data as JSON
    • Example: Returning Custom HTTP Status Codes
    • Explanation: Generating Appropriate Responses

1. Creating a Web API Controller

Example: Creating a Basic Web API Controller

csharp
[ApiController] [Route("api/[controller]")] public class UserController : ControllerBase { // Controller actions }

Explanation: Understanding the Structure of a Web API Controller

To create a Web API controller, you need to define a class that inherits from the ControllerBase class. The [ApiController] attribute is used to indicate that this class is an API controller. The [Route] attribute specifies the base route for all actions within the controller. In this example, the base route is set as "api/[controller]," where [controller] is a token that will be replaced with the controller name (in this case, "UserController").

2. Routing in Web API Controllers

Example: Configuring Routes for Web API Controllers

csharp
[Route("api/[controller]")] public class UserController : ControllerBase { [HttpGet] public IActionResult GetAllUsers() { // Retrieve all users return Ok(users); } [HttpGet("{id}")] public IActionResult GetUserById(int id) { // Retrieve user by ID return Ok(user); } // Other actions }

Explanation: Mapping Routes to Controller Actions

In the example above, two different routes are configured for the UserController. The [Route] attribute is used at the class level to set the base route for all actions. Additionally, specific routes can be defined for each action using attributes like [HttpGet] and [HttpPost]. In the first action, [HttpGet] is used without any additional route parameters, so it will match the route "api/user" (GET request). The second action uses [HttpGet("{id}")], which means it will match routes with an additional parameter representing the user ID, such as "api/user/1" (GET request).

3. Handling HTTP Requests

Example: Handling GET Requests

csharp
[HttpGet("{id}")] public IActionResult GetUserById(int id) { var user = userRepository.GetUserById(id); if (user == null) return NotFound(); return Ok(user); }

Example: Handling POST Requests

csharp
[HttpPost] public IActionResult CreateNewUser(UserDto userDto) { var newUser = userRepository.CreateUser(userDto); return CreatedAtAction(nameof(GetUserById), new { id = newUser.Id }, newUser); }

Example: Handling PUT and DELETE Requests

csharp
[HttpPut("{id}")] public IActionResult UpdateUser(int id, UserDto userDto) { var updatedUser = userRepository.UpdateUser(id, userDto); if (updatedUser == null) return NotFound(); return Ok(updatedUser); } [HttpDelete("{id}")] public IActionResult DeleteUser(int id) { var deletedUser = userRepository.DeleteUser(id); if (deletedUser == null) return NotFound(); return NoContent(); }

Explanation: Processing Different Types of Requests

Web API controllers can handle various types of HTTP requests. In these examples, we cover the most common ones:

  • GET request: The GetUserById action retrieves a user by ID from a repository. If the user is found, it returns an Ok response with the user's details. Otherwise, it returns a NotFound response.

  • POST request: The CreateNewUser action creates a new user based on the provided UserDto object. It returns a CreatedAtAction response with the newly created user's details and a location header pointing to the GetUserById action.

  • PUT request: The UpdateUser action updates an existing user identified by the ID. It returns an Ok response with the updated user's details if successful. Otherwise, it returns a NotFound response.

  • DELETE request: The DeleteUser action deletes an existing user identified by the ID. It returns a NoContent response if the user is successfully deleted. Otherwise, it returns a NotFound response.

4. Returning Responses

Example: Returning Data as JSON

csharp
[HttpGet] public IActionResult GetAllUsers() { var users = userRepository.GetAllUsers(); return Ok(users); }

Example: Returning Custom HTTP Status Codes

csharp
[HttpGet("{id}")] public IActionResult GetUserById(int id) { var user = userRepository.GetUserById(id); if (user == null) return StatusCode(404, "User not found"); return Ok(user); }

Explanation: Generating Appropriate Responses

When returning responses from Web API controllers, you can use various methods provided by the ControllerBase class:

  • Ok: Returns an HTTP 200 (OK) response with the provided data.

  • CreatedAtAction: Returns an HTTP 201 (Created) response with the provided data and a location header pointing to a specific action.

  • NotFound: Returns an HTTP 404 (Not Found) response.

  • NoContent: Returns an HTTP 204 (No Content) response.

  • StatusCode: Allows you to return a custom HTTP status code along with a message or object.

In the examples above, Ok is used to return data as JSON, and StatusCode is used to return custom status codes with messages.

Post a Comment

0 Comments