Building Your First Microservice with .NET
This tutorial guides you through the fundamental steps of creating a simple microservice using .NET and ASP.NET Core. We'll focus on core concepts and best practices to get you started quickly.
Step 1: Project Setup
Start by creating a new ASP.NET Core Web API project. Open your terminal or command prompt and navigate to your desired project directory.
dotnet new webapi -n MyFirstMicroservice
cd MyFirstMicroservice
This command creates a new project named MyFirstMicroservice
with the necessary configuration for a Web API.
Step 2: Define Your Service's Responsibility
A microservice should have a single, well-defined responsibility. For this example, let's create a simple service that manages a list of products.
Create a new folder named Models
in your project root. Inside Models
, create a file named Product.cs
:
namespace MyFirstMicroservice.Models
{
public class Product
{
public int Id { get; set; }
public string Name { get; set; }
public decimal Price { get; set; }
}
}
Step 3: Create a Controller
Controllers handle incoming HTTP requests. Create a new folder named Controllers
. Inside Controllers
, create a file named ProductsController.cs
:
using Microsoft.AspNetCore.Mvc;
using MyFirstMicroservice.Models;
using System.Collections.Generic;
using System.Linq;
namespace MyFirstMicroservice.Controllers
{
[ApiController]
[Route("api/[controller]")]
public class ProductsController : ControllerBase
{
private static List<Product> _products = new List<Product>
{
new Product { Id = 1, Name = "Laptop", Price = 1200.00m },
new Product { Id = 2, Name = "Keyboard", Price = 75.50m },
new Product { Id = 3, Name = "Mouse", Price = 25.00m }
};
[HttpGet]
public ActionResult<IEnumerable<Product>> GetAllProducts()
{
return Ok(_products);
}
[HttpGet("{id}")]
public ActionResult<Product> GetProductById(int id)
{
var product = _products.FirstOrDefault(p => p.Id == id);
if (product == null)
{
return NotFound();
}
return Ok(product);
}
[HttpPost]
public ActionResult<Product> CreateProduct([FromBody] Product newProduct)
{
if (newProduct == null)
{
return BadRequest();
}
newProduct.Id = _products.Count > 0 ? _products.Max(p => p.Id) + 1 : 1;
_products.Add(newProduct);
return CreatedAtAction(nameof(GetProductById), new { id = newProduct.Id }, newProduct);
}
}
}
This controller exposes endpoints for getting all products, getting a product by ID, and creating a new product. We're using a static list for simplicity; in a real application, you would use a database.
Step 4: Run Your Microservice
You can now run your microservice from the terminal:
dotnet run
Your service will typically start on http://localhost:5000
or https://localhost:5001
. You can test the endpoints using tools like Postman or by navigating to them in your browser.
- Get All Products: https://localhost:5001/api/products
- Get Product by ID (e.g., 1): https://localhost:5001/api/products/1
To test the POST
endpoint, you'll need to use a tool like Postman and send a POST request to https://localhost:5001/api/products
with a JSON body representing a new product.
Next Steps
Congratulations on building your first microservice! From here, you can explore:
- Data Persistence: Integrate with a database (e.g., SQL Server, PostgreSQL) using Entity Framework Core.
- API Design: Learn about RESTful API principles and best practices.
- Containerization: Package your service using Docker for easy deployment.
- Communication: Explore patterns for inter-service communication (e.g., gRPC, message queues).
- Error Handling and Logging: Implement robust error handling and logging mechanisms.