ASP.NET Core Web API is a cross-platform, high-performance framework by Microsoft used to build RESTful services for web, mobile, and microservices.
[ApiController]
[Route("api/products")]
public class ProductsController : ControllerBase
{
[HttpGet]
public IActionResult GetProducts()
{
return Ok(new[] { "Laptop", "Mobile" });
}
}
REST (Representational State Transfer) is an architectural style that uses HTTP methods for CRUD operations.
[HttpGet] // Read
[HttpPost] // Create
[HttpPut] // Update
[HttpDelete] // Delete
Routing maps URLs to controller actions.
[Route("api/products")]
[HttpGet("{id}")]
public IActionResult GetProduct(int id)
{
return Ok(new { Id = id, Name = "Laptop" });
}
ControllerBase is a base class for APIs without views. It provides helper methods like Ok(), NotFound().
public class ProductsController : ControllerBase
{
[HttpGet]
public IActionResult Get() => Ok("Hello API");
}
IActionResult represents HTTP responses with status codes.
return Ok(products); // 200 OK
return Created(uri, product); // 201 Created
return NoContent(); // 204 No Content
return BadRequest(); // 400 Bad Request
return Unauthorized(); // 401 Unauthorized
return Forbidden(); // 403 Forbidden
return NotFound(); // 404 Not Found
return Conflict(); // 409 Conflict
return UnsupportedMediaType(); // 415 Unsupported Media Type
return InternalServerError(); // 500 Internal Server Error
return Redirect(url); // 302 Found (Redirect)
Automatically maps request data to parameters or models.
[HttpPost]
public IActionResult CreateProduct(Product product)
{
return Ok(product);
}
Ensures correct data before processing.
public class Product
{
[Required]
public string Name { get; set; }
[Range(1, 10000)]
public decimal Price { get; set; }
}
Injects dependencies into classes for loose coupling.
builder.Services.AddScoped();
public class HomeController : Controller
{
private readonly IMessageService _service;
public HomeController(IMessageService service) => _service = service;
}
Middleware handles requests/responses in a pipeline.
app.Use(async (context, next) =>
{
Console.WriteLine("Incoming request");
await next();
Console.WriteLine("Outgoing response");
});
Configuration file used for storing settings.
{
"ConnectionStrings": {
"Default": "Server=.;Database=TestDb;"
}
}
Swagger provides API documentation and UI testing.
builder.Services.AddSwaggerGen();
app.UseSwagger();
app.UseSwaggerUI();
JSON is a lightweight format used for data exchange.
{ "id": 1, "name": "Laptop" }
Used to fetch data.
[HttpGet("{id}")]
public IActionResult GetProduct(int id) => Ok(new { Id = id, Name = "Laptop" });
Used to create data.
[HttpPost]
public IActionResult CreateProduct(Product product)
{
return CreatedAtAction(nameof(GetProduct), new { id = 1 }, product);
}
PUT replaces full resource, PATCH updates partially.
[HttpPut("{id}")]
public IActionResult UpdateProduct(int id, Product product) => Ok(product);