- Use
[ApiController]and[Route("api/[controller]")]attributes on controllers. - Use
[HttpGet],[HttpPost], etc., to define actions.
[ApiController] and [Route("api/[controller]")] attributes on controllers.[HttpGet], [HttpPost], etc., to define actions.
Creating an API in ASP.NET Core is straightforward thanks to the built-in Web API template. Here's a step-by-step guide.
Step 1: Create a New ASP.NET Core Web API Project
Using the .NET CLI:
Or in Visual Studio:
Step 2: Examine the Project Structure
A typical project structure looks like:
Step 3: Create a Model
Create a
Modelsfolder and add aProductclass.Step 4: Create a Controller
Inside the
Controllersfolder, createProductsController.cs.Step 5: Configure Services
In .NET 6+ (
Program.cs):Step 6: Run the API
Example output:
Step 7: Test the API
Open:
Swagger UI allows you to test endpoints directly from the browser.
Example response from
GET /api/products:Step 8: Add a POST Endpoint
Add a GET by Id endpoint:
Step 9: Add PUT Endpoint
Step 10: Add DELETE Endpoint
Complete CRUD Endpoints
/api/products/api/products/{id}/api/products/api/products/{id}/api/products/{id}Next Steps for Production Applications
After creating a basic API, you'll typically add:
This is the standard approach for building RESTful APIs in modern ASP.NET Core applications.