From 46e22a442cb34b25275241b0bca5002ac952e7ea Mon Sep 17 00:00:00 2001 From: Marcello Lamonaca Date: Wed, 1 Sep 2021 22:57:15 +0200 Subject: [PATCH] Add .NET 6 Minimal APIs Notes --- DotNet/ASP.NET/Minimal API.md | 87 +++++++++++++++++++++++++++++++++++ 1 file changed, 87 insertions(+) create mode 100644 DotNet/ASP.NET/Minimal API.md diff --git a/DotNet/ASP.NET/Minimal API.md b/DotNet/ASP.NET/Minimal API.md new file mode 100644 index 0000000..b6ade6c --- /dev/null +++ b/DotNet/ASP.NET/Minimal API.md @@ -0,0 +1,87 @@ +# Minimal API + +**NOTE**: Requires .NET 6+ + +## REST API + +```cs +var builder = WebApplication.CreateBuilder(args); +builder.Services.AddSingleton(); +builder.Services.AddScoped(); +builder.Services.AddTransient(); + +var app = builder.Build(); + +app.MapGet("/route/{id}", (IService service, int id) => { + // code to get entity from db here + return entity is not null ? Results.Ok(entity) : Results.NotFound(); +}); + +app.MapPost("/route", (IService service, Entity entity) => { + // code to add entity to db here + return Results.Created($"/route/{entity.Id}", obj); +}); + +app.Run(); +//or +app.RunAsync(); + +public class Entity(int Id, string Name); +``` + +### Swagger + +```cs +var builder = WebApplication.CreateBuilder(args); +builder.Services.AddEndpointsApiExplorer(); +builder.Services.AddSwaggerGen(); + +var app = builder.Build(); + +if (app.Environment.IsDevelopment()) +{ + app.UseDeveloperExceptionPage(); +} + +app.UseSwagger(); +app.MapGet("/", () => "Hello World!"); +app.UseSwaggerUI(); +app.Run(); +``` + +### MVC + +```cs +var builder = WebApplication.CreateBuilder(args); + +// Add services to the container. +builder.Services.AddControllersWithViews(); + +var app = builder.Build(); + +// Configure the HTTP request pipeline. +if (app.Environment.IsDevelopment()) +{ + app.UseDeveloperExceptionPage(); +} +else +{ + app.UseExceptionHandler("/Home/Error"); + + // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts. + app.UseHsts(); +} + +app.UseHttpsRedirection(); +app.UseStaticFiles(); + +app.UseRouting(); + +app.UseAuthorization(); + +app.MapControllerRoute( + name: "default", + pattern: "{controller=Home}/{action=Index}/{id?}"); + +app.Run(); +```