DotNet 7
Minimal API
Minimerer boilerplate for små tjenester
Nytt prosjekt
dotnet new web -o MyApi
Hello World
Program.cs
var builder = WebApplication.CreateBuilder(args);
var app = builder.Build();
app.MapGet("/", () => "Hello World!");
app.Run();
HTTP Verb, Dependency Injection og Autentisering
Program.cs
using MiniApi;
using Microsoft.AspNetCore.Authorization;
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddScoped<IJokeService, JokeService>();
builder.Services.AddAuthentication();
var app = builder.Build();
app.MapGet("/", () => "Hello World!");
app.MapGet("/joke", (IJokeService jokeService) => jokeService.GetJoke());
app.MapGet("/secret", [Authorize] () => "Secret content");
app.MapPost("/jokes", (string joke) => $"Postet vits: {joke}");
app.MapPut("/jokes", (string joke) => $"Puttet vits: {joke}");
app.MapDelete("/jokes", (string joke) => $"Slettet vits: {joke}");
app.MapPost("/jokes", (Joke joke) => $"Postet vits av {joke.author}: {joke.content}");
app.Run();
record Joke(string author, string content);
namespace MiniApi;
public interface IJokeService
{
public string GetJoke();
}
public class JokeService : IJokeService
{
public string GetJoke()
{
return "What does an angry pepper do? It gets jalapeño face.";
}
}