Framing the Objective
I'm focused on the fundamental need: a ready-to-use C# ASP.NET Core Web API template, efficiently set up to use Entity Framework Core. My current task is understanding the core requirements of this boilerplate to lay the groundwork for a robust and easily customizable solution.
Defining the Architecture
I've been refining the architectural components: Focusing on a "Clean Architecture" lite approach for the initial boilerplate. My emphasis is now on the essential layers: Controller, Service, and Context. This design simplifies the initial setup while allowing for future expansion. The model and DTO structures are now under development.
Constructing the Foundation
I'm now detailing the core components, focusing on a straightforward controller structure. The product model and DB context are ready. Currently, I'm working through the Program.cs configuration, specifically the DI container setup, integrating the database context and controllers. I'll include Swagger as well, as it is standard in the modern Web API project.
Developing the Blueprint
I'm now deep-diving into the practical coding phases, working on the controller, and establishing the foundational structure for the entire project. Focusing on the Program.cs file and its crucial DI container setup is key. I'll include the Swagger documentation as standard in the resulting Web API. Then, I'll incorporate the DB context and controllers, and ensure the project builds correctly.
Devising the Implementation
I'm now fully immersed in the coding process, meticulously crafting the foundational files. The Model, DB context, and controller structures are solid. The Program.cs file is next, focusing on configuring dependency injection and ensuring everything wires together. After that, I'll integrate Swagger, and I will perform tests to verify proper functionality.
Formulating the Solution
I'm now fully immersed in the coding phase, meticulously creating the core components. The model, database context, and controller structures are complete and ready for the Program.cs configuration, specifically the DI container setup. After this, I'll include the necessary NuGet packages. I will also incorporate Swagger, and run tests to ensure proper functionality.
This is a complete, modern (NET 6/7/8+) boilerplate for an ASP.NET Core Web API using Entity Framework Core with SQL Server.
1. Project Setup & Dependencies
First, open your terminal/command prompt and run these commands to create the project and install the necessary NuGet packages.
# Create new Web API project
dotnet new webapi -n MyWebApi
cd MyWebApi
# Add Entity Framework Core packages (assuming SQL Server)
dotnet add package Microsoft.EntityFrameworkCore
dotnet add package Microsoft.EntityFrameworkCore.SqlServer
dotnet add package Microsoft.EntityFrameworkCore.Tools
2. Project Structure & Code
Here is the file structure and the code for each component.
A. The Model (Models/Product.cs)
Create a folder named Models and add this class. This represents your database table.
namespace MyWebApi.Models
{
public class Product
{
public int Id { get; set; }
public string Name { get; set; } = string.Empty;
public string Description { get; set; } = string.Empty;
public decimal Price { get; set; }
}
}
B. The Database Context (Data/AppDbContext.cs)
Create a folder named Data and add this class. This acts as the bridge between your code and the database.
using Microsoft.EntityFrameworkCore;
using MyWebApi.Models;
namespace MyWebApi.Data
{
public class AppDbContext : DbContext
{
public AppDbContext(DbContextOptions<AppDbContext> options) : base(options)
{
}
// This DbSet represents the table in the database
public DbSet<Product> Products { get; set; }
}
}
C. Connection String (appsettings.json)
Open your appsettings.json file and add the ConnectionStrings section.
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft.AspNetCore": "Warning"
}
},
"AllowedHosts": "*",
"ConnectionStrings": {
"DefaultConnection": "Server=.;Database=MyWebApiDb;Trusted_Connection=True;TrustServerCertificate=True;"
}
}
D. Dependency Injection (Program.cs)
Update Program.cs to register Entity Framework and configure the HTTP pipeline.
using Microsoft.EntityFrameworkCore;
using MyWebApi.Data;
var builder = WebApplication.CreateBuilder(args);
// Add services to the container.
// 1. Register Entity Framework Context
builder.Services.AddDbContext<AppDbContext>(options =>
options.UseSqlServer(builder.Configuration.GetConnectionString("DefaultConnection")));
builder.Services.AddControllers();
// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();
var app = builder.Build();
// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
app.UseSwagger();
app.UseSwaggerUI();
}
app.UseHttpsRedirection();
app.UseAuthorization();
app.MapControllers();
app.Run();
E. The Controller (Controllers/ProductsController.cs)
Create a new controller to handle CRUD operations.
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using MyWebApi.Data;
using MyWebApi.Models;
namespace MyWebApi.Controllers
{
[Route("api/[controller]")]
[ApiController]
public class ProductsController : ControllerBase
{
private readonly AppDbContext _context;
public ProductsController(AppDbContext context)
{
_context = context;
}
// GET: api/Products
[HttpGet]
public async Task<ActionResult<IEnumerable<Product>>> GetProducts()
{
return await _context.Products.ToListAsync();
}
// GET: api/Products/5
[HttpGet("{id}")]
public async Task<ActionResult<Product>> GetProduct(int id)
{
var product = await _context.Products.FindAsync(id);
if (product == null)
{
return NotFound();
}
return product;
}
// POST: api/Products
[HttpPost]
public async Task<ActionResult<Product>> PostProduct(Product product)
{
_context.Products.Add(product);
await _context.SaveChangesAsync();
return CreatedAtAction(nameof(GetProduct), new { id = product.Id }, product);
}
// PUT: api/Products/5
[HttpPut("{id}")]
public async Task<IActionResult> PutProduct(int id, Product product)
{
if (id != product.Id)
{
return BadRequest();
}
_context.Entry(product).State = EntityState.Modified;
try
{
await _context.SaveChangesAsync();
}
catch (DbUpdateConcurrencyException)
{
if (!ProductExists(id))
{
return NotFound();
}
else
{
throw;
}
}
return NoContent();
}
// DELETE: api/Products/5
[HttpDelete("{id}")]
public async Task<IActionResult> DeleteProduct(int id)
{
var product = await _context.Products.FindAsync(id);
if (product == null)
{
return NotFound();
}
_context.Products.Remove(product);
await _context.SaveChangesAsync();
return NoContent();
}
private bool ProductExists(int id)
{
return _context.Products.Any(e => e.Id == id);
}
}
}
3. Run Migrations & Start
Now that the code is in place, you need to create the database and run the app.
-
Create the Migration:
dotnet ef migrations add InitialCreate
-
Update the Database:
dotnet ef database update
-
Run the Application:
dotnet run
You can now navigate to https://localhost:xxxx/swagger in your browser to test the API using the Swagger UI.
4. (Optional) Best Practices for Production
While the above is a standard boilerplate, in a real-world scenario, you should consider adding:
- DTOs (Data Transfer Objects): Don't expose your
Product database entity directly to the API. Create a ProductDto and map between them.
- Repository Pattern: Instead of injecting
AppDbContext directly into the Controller, create an IProductRepository to abstract database logic.
- Global Exception Handling: Middleware to catch errors and return standardized JSON error responses.