Web API based on Minimal APIs in ASP.NET Core

Web API based on Minimal APIs

Minimal APIs is a way to quickly build REST APIs in ASP.NET Core, which can build full-featured REST APIs with the least amount of code. For example, the following three lines of code:

var app = WebApplication.Create(args);
app.MapGet("/", () => "Hello World!");
app.Run();

It can be implemented to return "Hello World!" when requesting the root directory node of the website.
This method of Web API can be used to build microservices and websites with minimal functions.

Map HTTP requests

The following code maps the urls of several HTTP requests to Lambda functions, which are:

  • HTTP GET, /todoitems, get all todoitems
  • HTTP GET, /todoitems/complete, to get all completed todoitems
  • HTTP GET, /todoitems/{id}, get the todoitem of a certain id
  • HTTP Post, /todoitems, add a todoitem
  • HTTP PUT, /todoitems/{id}, modify the todoitem of a certain id
  • HTTP DELETE, /todoitems/{id}, delete a todoitem with an id
using Microsoft.EntityFrameworkCore;

var builder = WebApplication.CreateBuilder(args);
builder.Services.AddDbContext<TodoDb>(opt => opt.UseInMemoryDatabase("TodoList"));
builder.Services.AddDatabaseDeveloperPageExceptionFilter();
var app = builder.Build();

app.MapGet("/todoitems", async (TodoDb db) =>
    await db.Todos.ToListAsync());

app.MapGet("/todoitems/complete", async (TodoDb db) =>
    await db.Todos.Where(t => t.IsComplete).ToListAsync());

app.MapGet("/todoitems/{id}", async (int id, TodoDb db) =>
    await db.Todos.FindAsync(id)
        is Todo todo
            ? Results.Ok(todo)
            : Results.NotFound());

app.MapPost("/todoitems", async (Todo todo, TodoDb db) =>
{
    
    
    db.Todos.Add(todo);
    await db.SaveChangesAsync();

    return Results.Created($"/todoitems/{
      
      todo.Id}", todo);
});

app.MapPut("/todoitems/{id}", async (int 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();
});

app.MapDelete("/todoitems/{id}", async (int 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();

Guess you like

Origin blog.csdn.net/cuit/article/details/132612773