Web APIs
Introduction
ASP.NET Core is a cross-platform, high-performance framework for building modern, cloud-enabled, Internet-connected applications. With ASP.NET Core, you can build web apps, mobile backends, and APIs. This tutorial will guide you through creating a web API with ASP.NET Core from scratch.
Setting Up the Development Environment
Before you start, ensure you have the following installed:
- Visual Studio 2019 or later
- .NET Core SDK
Example: Installing .NET Core SDK
https://dotnet.microsoft.com/download/dotnet-core
Creating a New ASP.NET Core Web API Project
Open Visual Studio and create a new project:
- Select "Create a new project".
- Choose "ASP.NET Core Web Application" and click "Next".
- Name your project and select the location to save it. Click "Create".
- In the "Create a new ASP.NET Core Web Application" dialog, select "API" and click "Create".
Understanding the Project Structure
The project template creates a simple project structure:
- Controllers - Contains the API controllers.
- Models - Contains the data models.
- Program.cs - Contains the entry point of the application.
- Startup.cs - Configures services and the app's request pipeline.
Creating a Model
In this tutorial, we will create a simple model for a "Product". Add a new class named Product.cs
in the Models
folder:
Example: Product Model
public class Product
{
public int Id { get; set; }
public string Name { get; set; }
public decimal Price { get; set; }
}
Creating a Controller
Create a new controller named ProductsController.cs
in the Controllers
folder:
Example: Products Controller
using Microsoft.AspNetCore.Mvc;
using System.Collections.Generic;
using System.Linq;
namespace WebAPITutorial.Controllers
{
[Route("api/[controller]")]
[ApiController]
public class ProductsController : ControllerBase
{
private static readonly List Products = new List
{
new Product { Id = 1, Name = "Product1", Price = 10.0M },
new Product { Id = 2, Name = "Product2", Price = 20.0M }
};
[HttpGet]
public ActionResult> GetProducts()
{
return Products;
}
[HttpGet("{id}")]
public ActionResult GetProduct(int id)
{
var product = Products.FirstOrDefault(p => p.Id == id);
if (product == null)
{
return NotFound();
}
return product;
}
[HttpPost]
public ActionResult CreateProduct(Product product)
{
product.Id = Products.Count + 1;
Products.Add(product);
return CreatedAtAction(nameof(GetProduct), new { id = product.Id }, product);
}
}
}
Configuring the Application
Ensure that the Startup.cs
file is correctly configured to use controllers:
Example: Startup.cs Configuration
public void ConfigureServices(IServiceCollection services)
{
services.AddControllers();
}
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseHttpsRedirection();
app.UseRouting();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
}
Testing the API
Run the application by pressing F5
or clicking the "Run" button in Visual Studio. Use a tool like Postman to test your API endpoints:
- GET
https://localhost:5001/api/products
- Retrieve all products. - GET
https://localhost:5001/api/products/1
- Retrieve a product by ID. - POST
https://localhost:5001/api/products
- Create a new product.
Conclusion
Congratulations! You have created a simple Web API with ASP.NET Core. This tutorial covered the basics of setting up a new project, creating models and controllers, configuring the application, and testing the API. From here, you can extend the API with more features and deploy it to a cloud service.