Zum Hauptinhalt springen

.NET API

Projekt

Projekt erstellen

dotnet new web --name WebApi --framework net8.0

Projekt starten

cd WebApi
dotnet run

Projekt-Einstellungen

launchSettings.json

In der Datei Properties/launchSettings.json befinden sich die Einstellungen für das Projekt.

Inhalt:

  • profiles/http: http-Profil
    • enthält unter applicationUrl Port, über welchen die Anwendung erreichbar ist
    • kann beliebig geändert werden, sofern dieser Port nicht schon benutzt ist oder nicht existiert

appsettings.json

In der Datei appsettings.json befinden sich die Einstellungen für die Anwendung.

Inhalt:

  • Logging: Logging-Einstellungen
    • LogLevel: Log-Level für verschiedene Bereiche
  • weitere eigene Einstellungen ...

Beispiel:

{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft.AspNetCore": "Warning"
}
},
"AllowedHosts": "*",
"DatabaseSettings": {
"ConnectionString": "mongodb://user:pwd@mongodb:27017"
}
}

Mapping im Code mit gleichen Feldern wie appsettings.json:

public class SomeSettings
{
public string ConnectionString { get; set; } = "";
// ...
}

Projekt-Struktur

  • <solution name>
    • WebApi (C#-Projekt)
      • bin
      • obj
      • Properties
        • launchSettings.json
      • appsettings.Development.json
      • appsettings.json
      • Program.cs
      • WebApi.csproj
    • .gitignore
    • README.md

API-Controller

Program.cs:

// creates a builder to configure/build the application
var builder = WebApplication.CreateBuilder(args);

// create a singleton service that can be injected in every MapXXX method
builder.Services.AddSingleton<IMovieService, MongoMovieService>();

// get configuration section of appsettings.json and bind configuration section to a class with the same properties
var someSettings = builder.Configuration.GetSection("DatabaseSettings");
builder.Services.Configure<SomeSettings>(someSettings);

// finish the API configuration setup
var app = builder.Build();

// create all API endpoints

app.MapGet("/", () => "Minimal API Version 1.0");

app.MapGet("/check", (IMovieService movieService) =>
{
return movieService.Check(); // returns a simple string
});

app.MapPost("/api/movies", (IMovieService movieService, Movie movie) =>
{
movieService.CreateMovie(movie);
return Results.Ok($"movie with id {movie.Id} created"); // returns a 200 OK
});

app.MapGet("/api/movies", (IMovieService movieService) =>
{
return Results.Ok(movieService.GetMovies());
});

app.MapGet("/api/movies/{id}", (IMovieService movieService, string id) =>
{
Movie? movie = movieService.GetMovie(id);
if (movie == null)
{
return Results.NotFound($"movie with id {id} doesn't exist"); // returns a 404 Not Found
}

return Results.Ok(movie);
});

app.MapPut("/api/movies/{id}", (IMovieService movieService, string id, Movie movie) =>
{
if (movieService.UpdateMovie(id, movie))
{
return Results.Ok($"movie with id {id} updated");
}

return Results.NotFound($"movie with id {id} doesn't exist");
});

app.MapDelete("/api/movies/{id}", (IMovieService movieService, string id) =>
{
if (movieService.DeleteMovie(id))
{
return Results.Ok($"movie with id {id} deleted");
}

return Results.NotFound($"movie with id {id} doesn't exist");
});

// run the application on the configured port
app.Run();

API testen

Um eine Rest-API zu testen, gibt es unter anderem folgende Möglichkeiten:

Postman

  • Postman
  • eine der bekanntesten Anwendungen, um REST-APIs zu testen
  • Installation auf Linux
    snap install postman

Insomnia

Visual Studio Code Erweiterung

  • in Visual Studio Code mit der Erweiterung REST Client

  • Requests können in einer .http-Datei gespeichert werden: (hier requests.http)

    ### (divider)
    GET http://localhost:5001/check HTTP/1.1

    ###
    POST http://localhost:5001/api/values

    POST http://localhost:5001/api/movies
    Content-Type: application/json

    {
    "Title": "No Time To Die",
    "Year": 2000,
    "Summary": "This is a summary of the movie No TIme To Die!",
    "Actors": [
    "Actor 1",
    "Actor 2"
    ]
    }

OpenAPI und Swagger

Swagger-API-Dokumentation hinzufügen

Benötigte Packages:

dotnet add package Microsoft.AspNetCore.OpenApi
dotnet add package Swashbuckle.AspNetCore
var builder = WebApplication.CreateBuilder(args);

builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();

// ...

var app = builder.Build();

app.UseSwagger();
app.UseSwaggerUI();

// exclude from the OpenAPI documentation
app.MapGet("/", () => "Minimal API Version 1.0").ExcludeFromDescription();

app.MapGet("/api" =>
{
return "Welcome to the Minimal API!";
});

app.Run();