- Регистрация
- 1 Мар 2015
- Сообщения
- 1,481
- Баллы
- 155
? .NET Core's Minimal APIs offer a streamlined approach to building HTTP APIs with reduced boilerplate. This post walks you through creating a Todo list API from scratch, showcasing the simplicity and power of Minimal APIs.
Prerequisites
Create a Models directory and add a Todo.cs file:
namespace MinimalTodoApi.Models;
public class Todo
{
// Unique identifier for the Todo item
public Guid Id { get; set; }
// Name or description of the Todo item
public string? Name { get; set; }
// Indicates whether the Todo item is complete
public bool IsComplete { get; set; }
}
This simple model defines the structure of our Todo items.
Setting up the Database Context
Create a Data directory and add TodoDb.cs:
using Microsoft.EntityFrameworkCore;
using MinimalTodoApi.Models;
namespace MinimalTodoApi.Data;
// Represents the database context for the Todo application
public class TodoDb : DbContext
{
// Constructor that accepts DbContextOptions
public TodoDb(DbContextOptions<TodoDb> options) : base(options) { }
// Represents the collection of Todo items in the database
public DbSet<Todo> Todos { get; set; }
}
This class sets up our database context using Entity Framework Core.
Configuring the Minimal API Endpoints (Program.cs)
Now, let's define our API endpoints within Program.cs:
using Microsoft.EntityFrameworkCore;
using MinimalTodoApi.Data;
using MinimalTodoApi.Models;
var builder = WebApplication.CreateBuilder(args);
// Add the database context to the services container. This allows the database to be injected into the API endpoints.
builder.Services.AddDbContext<TodoDb>(options
=> options.UseSqlServer(builder.Configuration.GetConnectionString("MinimalTodo"))
);
var app = builder.Build();
// Configure the API endpoints
// Get all todo items
app.MapGet("/todos", async (TodoDb db) =>
await db.Todos.ToListAsync());
// Get completed todo items
app.MapGet("/todos/complete", async (TodoDb db) =>
await db.Todos.Where(t => t.IsComplete).ToListAsync());
// Get a specific todo item by ID
app.MapGet("/todos/{id}", async (Guid id, TodoDb db) =>
await db.Todos.FindAsync(id)
is Todo todo
? Results.Ok(todo)
: Results.NotFound());
// Create a new todo item
app.MapPost("/todos", async (Todo todo, TodoDb db) =>
{
db.Todos.Add(todo);
await db.SaveChangesAsync();
return Results.Created($"/todos/{todo.Id}", todo);
});
// Update an existing todo item
app.MapPut("/todos/{id}", async (Guid id, Todo inputTodo, TodoDb db) =>
{
var todo = await db.Todos.FindAsync(id);
if (todo is null) return Results.NotFound();
todo.Name = inputTodo.Name;
todo.IsComplete = inputTodo.IsComplete;
await db.SaveChangesAsync();
return Results.NoContent();
});
// Delete a todo item
app.MapDelete("/todos/{id}", async (Guid id, TodoDb db) =>
{
if (await db.Todos.FindAsync(id) is Todo todo)
{
db.Todos.Remove(todo);
await db.SaveChangesAsync();
return Results.NoContent();
}
return Results.NotFound();
});
app.Run();
Key improvements and explanations:
dotnet run
Your Todo API is now running!
Testing the API with Endpoints Explorer (Visual Studio)
Visual Studio provides a built-in tool to explore and test your API endpoints:
Conclusion
.NET Core Minimal APIs provide a powerful and elegant way to build APIs with minimal code. This Todo list example demonstrates the core concepts and provides a foundation for building more complex applications. Embrace the simplicity and efficiency of Minimal APIs in your next .NET project!
? Useful Links
?
?
Prerequisites
- .NET Core SDK (latest version recommended)
- A code editor (VS Code, JetBrains Rider, etc.)
- Basic understanding of C# and RESTful API concepts
- Visual Studio 2022 or later (for using Endpoints Explorer)
Create a new Web API project:
dotnet new webapi -o MinimalTodoApi
cd MinimalTodoApi
Install Entity Framework Core packages:
We'll use EF Core for data persistence. Install the necessary packages:
dotnet add package Microsoft.EntityFrameworkCore.SqlServer # Or your preferred database provider
dotnet add package Microsoft.EntityFrameworkCore.Design
dotnet add package Microsoft.EntityFrameworkCore.Tools
Create a Models directory and add a Todo.cs file:
namespace MinimalTodoApi.Models;
public class Todo
{
// Unique identifier for the Todo item
public Guid Id { get; set; }
// Name or description of the Todo item
public string? Name { get; set; }
// Indicates whether the Todo item is complete
public bool IsComplete { get; set; }
}
This simple model defines the structure of our Todo items.
Setting up the Database Context
Create a Data directory and add TodoDb.cs:
using Microsoft.EntityFrameworkCore;
using MinimalTodoApi.Models;
namespace MinimalTodoApi.Data;
// Represents the database context for the Todo application
public class TodoDb : DbContext
{
// Constructor that accepts DbContextOptions
public TodoDb(DbContextOptions<TodoDb> options) : base(options) { }
// Represents the collection of Todo items in the database
public DbSet<Todo> Todos { get; set; }
}
This class sets up our database context using Entity Framework Core.
Configuring the Minimal API Endpoints (Program.cs)
Now, let's define our API endpoints within Program.cs:
using Microsoft.EntityFrameworkCore;
using MinimalTodoApi.Data;
using MinimalTodoApi.Models;
var builder = WebApplication.CreateBuilder(args);
// Add the database context to the services container. This allows the database to be injected into the API endpoints.
builder.Services.AddDbContext<TodoDb>(options
=> options.UseSqlServer(builder.Configuration.GetConnectionString("MinimalTodo"))
);
var app = builder.Build();
// Configure the API endpoints
// Get all todo items
app.MapGet("/todos", async (TodoDb db) =>
await db.Todos.ToListAsync());
// Get completed todo items
app.MapGet("/todos/complete", async (TodoDb db) =>
await db.Todos.Where(t => t.IsComplete).ToListAsync());
// Get a specific todo item by ID
app.MapGet("/todos/{id}", async (Guid id, TodoDb db) =>
await db.Todos.FindAsync(id)
is Todo todo
? Results.Ok(todo)
: Results.NotFound());
// Create a new todo item
app.MapPost("/todos", async (Todo todo, TodoDb db) =>
{
db.Todos.Add(todo);
await db.SaveChangesAsync();
return Results.Created($"/todos/{todo.Id}", todo);
});
// Update an existing todo item
app.MapPut("/todos/{id}", async (Guid id, Todo inputTodo, TodoDb db) =>
{
var todo = await db.Todos.FindAsync(id);
if (todo is null) return Results.NotFound();
todo.Name = inputTodo.Name;
todo.IsComplete = inputTodo.IsComplete;
await db.SaveChangesAsync();
return Results.NoContent();
});
// Delete a todo item
app.MapDelete("/todos/{id}", async (Guid id, TodoDb db) =>
{
if (await db.Todos.FindAsync(id) is Todo todo)
{
db.Todos.Remove(todo);
await db.SaveChangesAsync();
return Results.NoContent();
}
return Results.NotFound();
});
app.Run();
Key improvements and explanations:
- Clear separation of concerns: Models in Models, database context in Data.
- Concise endpoint definitions: Minimal APIs make routing and logic clear.
- Dependency Injection: The TodoDb context is injected directly into the endpoint handlers.
- Asynchronous operations: Using async and await for non-blocking database calls.
Update appsettings.json:
Configure your database connection string. For example, using SQL Server:
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft.AspNetCore": "Warning"
}
},
"ConnectionStrings": {
"MinimalTodo": "Server=(localdb)\\mssqllocaldb;Database=MinimalTodo;Trusted_Connection=True;MultipleActiveResultSets=true"
},
"AllowedHosts": "*"
}
Create and apply migrations:
dotnet ef migrations add InitialCreate
dotnet ef database update
dotnet run
Your Todo API is now running!
Testing the API with Endpoints Explorer (Visual Studio)
Visual Studio provides a built-in tool to explore and test your API endpoints:
- Open Endpoints Explorer: In Visual Studio, go to View > Other Windows > Endpoints Explorer.
- Locate your API endpoints: The Endpoints Explorer will display a list of all available API endpoints in your project. You should see the /todos endpoints listed.
- Test the endpoints: You can right-click on an endpoint and select "Generate Request" to create a sample HTTP request. Modify the request as needed (e.g., add a request body for POST/PUT requests) and then click "Send Request" to test the endpoint. The response will be displayed in a separate window.
Conclusion
.NET Core Minimal APIs provide a powerful and elegant way to build APIs with minimal code. This Todo list example demonstrates the core concepts and provides a foundation for building more complex applications. Embrace the simplicity and efficiency of Minimal APIs in your next .NET project!
? Useful Links
?
?