Getting Started with ASP.NET Core Web API
A beginner's guide to building your first REST API with ASP.NET Core. Learn about the basic project structure, controllers, and how to use dependency injection to build clean, testable APIs.
ASP.NET Core is Microsoft's modern, open-source, and cross-platform framework for building web applications and services. One of its most common use cases is for building RESTful APIs that can be consumed by web browsers, mobile apps, or other backend services.
Let's walk through the fundamentals of creating your first Web API with ASP.NET Core 3.1.
Creating Your First Project
Getting started is simple with the .NET CLI.
# Create a new Web API project
dotnet new webapi -n MyFirstApi
cd MyFirstApi
This command scaffolds a new project with a basic structure, including a sample WeatherForecastController
.
The Core Components
Let's look at the key files in the project.
Program.cs
This is the entry point for your application. Its main job is to create and run a web host.
public class Program
{
public static void Main(string[] args)
{
CreateHostBuilder(args).Build().Run();
}
public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.ConfigureWebHostDefaults(webBuilder =>
{
webBuilder.UseStartup<Startup>();
});
}
Startup.cs
This is where you configure your application's services and its request processing pipeline.
public class Startup
{
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.AddControllers();
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseRouting();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
}
}
ConfigureServices
: This is where you register your application's services with the built-in dependency injection (DI) container.services.AddControllers()
registers the services needed for controllers.Configure
: This is where you define the middleware pipeline, which is how your application handles HTTP requests.app.UseRouting()
andapp.MapControllers()
work together to route incoming requests to the correct controller action.
Controllers and Actions
A controller is a class that handles HTTP requests. It's a collection of public methods called actions. When a request comes in, the routing middleware selects a controller and an action to execute based on the request URL.
By convention, controllers live in the Controllers
directory and inherit from ControllerBase
.
Let's create a simple ProductsController
.
// Controllers/ProductsController.cs
using Microsoft.AspNetCore.Mvc;
using System.Collections.Generic;
[ApiController]
[Route("api/[controller]")]
public class ProductsController : ControllerBase
{
private static readonly List<string> _products = new List<string>
{
"Laptop", "Mouse", "Keyboard"
};
// GET: api/products
[HttpGet]
public ActionResult<IEnumerable<string>> Get()
{
return Ok(_products);
}
// GET: api/products/1
[HttpGet("{id}")]
public ActionResult<string> Get(int id)
{
if (id < 0 || id >= _products.Count)
{
return NotFound();
}
return Ok(_products[id]);
}
}
Let's break this down:
[ApiController]
: This attribute enables several helpful features for API development, like automatic model validation.[Route("api/[controller]")]
: This defines the route template for the controller.[controller]
is a token that is replaced with the controller's name (Products
), so the base route for this controller is/api/products
.[HttpGet]
: This attribute marks a method as an action that handles HTTP GET requests.ActionResult<T>
: This is the standard return type for actions. It allows you to return either a specific type (like astring
orList<string>
) or an HTTP status code result (likeOk()
,NotFound()
, orBadRequest()
).
Running Your API
You can run your API from the command line:
dotnet run
Now you can make requests to your API:
GET http://localhost:5000/api/products
will return a JSON array of all products.GET http://localhost:5000/api/products/1
will return the string "Mouse".
Conclusion
ASP.NET Core provides a powerful, modern, and high-performance framework for building REST APIs. With its strong conventions, built-in dependency injection, and flexible middleware pipeline, it gives you all the tools you need to build robust and scalable services. This simple example is just the starting point for a rich ecosystem of features designed to make API development in .NET a first-class experience.