Back to Tutorials

Building REST APIs with C# ASP.NET Core

ASP.NET Core Setup

ASP.NET Core is a cross-platform, high-performance framework for building modern APIs.

Creating Web API

# Create new API project
dotnet new webapi -n MyApi

# Run the application
dotnet run

Controller Example

using Microsoft.AspNetCore.Mvc;

namespace MyApi.Controllers;

[ApiController]
[Route("api/[controller]")]
public class UsersController : ControllerBase
{
    [HttpGet]
    public async Task<ActionResult<IEnumerable<User>>> GetUsers()
    {
        var users = await _context.Users.ToListAsync();
        return users;
    }
    
    [HttpPost]
    public async Task<ActionResult<User>> CreateUser(User user)
    {
        _context.Users.Add(user);
        await _context.SaveChangesAsync();
        return CreatedAtAction(nameof(GetUser), new { id = user.Id }, user);
    }
}

Best Practices

  • Use async/await for all operations
  • Implement proper error handling
  • Use DTOs for request/response
  • Enable CORS properly
  • Use dependency injection