</>
Skip to content
ASP lessons (33/40)

ASP — ASP.NET Web API

Create API

dotnet new webapi -n MyApi
cd MyApi
dotnet run

Controller

[ApiController]
[Route("api/[controller]")]
public class ProductsController : ControllerBase
{
    private readonly IProductService _service;
    
    public ProductsController(IProductService service)
    {
        _service = service;
    }
    
    [HttpGet]
    public IActionResult GetAll()
    {
        return Ok(_service.GetAll());
    }
    
    [HttpGet("{id}")]
    public IActionResult GetById(int id)
    {
        var product = _service.GetById(id);
        if (product == null) return NotFound();
        return Ok(product);
    }
    
    [HttpPost]
    public IActionResult Create([FromBody] Product product)
    {
        var created = _service.Create(product);
        return CreatedAtAction(nameof(GetById), new { id = created.Id }, created);
    }
}

HTTP Methods

MethodAction
GETRead
POSTCreate
PUTUpdate
DELETEDelete

Mini Practice

  1. Create Web API project
  2. Create controller
  3. Implement CRUD
  4. Test with Postman

Up Next

Continue with ASP.NET Routing — routing.

Related Topics

Frequently Asked Questions about ASP.NET Web API

What is ASP.NET Web API in ASP?

ASP.NET Web API is a fundamental concept in ASP. This lesson explains it step by step with clear examples, making it easy for beginners to understand.

How do I learn ASP.NET Web API?

Start by reading the explanation above, then try the code examples. Practice by modifying the examples and experimenting with different values. Hands-on practice is the best way to learn ASP.NET Web API.

Why is ASP.NET Web API important in ASP?

ASP.NET Web API is essential for ASP development. Understanding this concept will help you write better code and solve real-world problems more effectively.