.NET and ASP.NET Core 10 cheatsheet

.NET and ASP.NET Core 10: ASP.NET Core code

7 common .NET and ASP.NET Core 10 tasks.

Write a minimal API

Define endpoints without controllers.

var builder = WebApplication.CreateBuilder(args);
var app = builder.Build();

app.MapGet("/", () => "Hello World!");
app.MapGet("/users/{id}", (int id) => Results.Ok(new { id }));

app.Run();

Register a service

Add a class to dependency injection with a scoped lifetime.

builder.Services.AddScoped<IUserService, UserService>();

Read configuration

Read a value from appsettings.json or an environment variable.

var connection = builder.Configuration["ConnectionStrings:Default"];

Set up user secrets

Create a secrets store for development, kept outside your repository.

dotnet user-secrets init

Store a development secret

Save a secret value without putting it in appsettings.json. Use your own value.

dotnet user-secrets set "ConnectionStrings:Default" "Host=localhost;Database=app;Username=app;Password=change-me"

Add authentication and authorization

Order matters: authentication goes before authorization.

app.UseAuthentication();
app.UseAuthorization();

Map controllers

Enable attribute-routed controllers.

builder.Services.AddControllers();
// ...
app.MapControllers();

Was this page helpful?