ASP.NET Core Cheatsheet
10xdev.blog/cheatsheets
# 1. .NET CLI for ASP.NET Core
# Create a new Web API project
dotnet new webapi -n MyApi

# Create a new MVC project
dotnet new mvc -n MyMvcApp

# Run the application
dotnet run

# Run with "hot reload" to apply changes on the fly
dotnet watch run

# Add a package (e.g., Entity Framework Core)
dotnet add package Microsoft.EntityFrameworkCore

# Manage EF Core migrations
dotnet ef migrations add InitialCreate
dotnet ef database update
# 2. Minimal APIs (.NET 6+)
// Program.cs
var builder = WebApplication.CreateBuilder(args);

// Add services to the container (Dependency Injection)
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();

var app = builder.Build();

// Configure the HTTP request pipeline
if (app.Environment.IsDevelopment())
{
    app.UseSwagger();
    app.UseSwaggerUI();
}

// Define endpoints
app.MapGet("/hello", () => "Hello, World!");

app.MapGet("/users/{id}", (int id) => $"User ID: {id}");

app.MapPost("/users", (User user) => {
    // Logic to create a user...
    return Results.Created($"/users/{user.Id}", user);
});

app.Run();

public record User(int Id, string Name);
# 3. MVC & API Controllers
using Microsoft.AspNetCore.Mvc;

[ApiController]
[Route("api/[controller]")]
public class UsersController : ControllerBase
{
    // GET: api/users
    [HttpGet]
    public ActionResult<IEnumerable<User>> GetUsers()
    {
        // ... logic to get users
        return new List<User>();
    }

    // GET: api/users/5
    [HttpGet("{id}")]
    public ActionResult<User> GetUser(int id)
    {
        // ... logic to get a single user
        if (user == null)
        {
            return NotFound();
        }
        return user;
    }
}
# 4. Dependency Injection (DI)
// In Program.cs or Startup.cs

// Registering services
builder.Services.AddTransient<IMyService, MyService>(); // New instance every time
builder.Services.AddScoped<IMyScopedService, MyScopedService>(); // New instance per request
builder.Services.AddSingleton<IMySingletonService, MySingletonService>(); // Single instance for app lifetime

// ---

// Injecting services into a controller's constructor
public class MyController : ControllerBase
{
    private readonly IMyService _myService;

    public MyController(IMyService myService)
    {
        _myService = myService;
    }
}
# 5. Entity Framework Core
using Microsoft.EntityFrameworkCore;

// 1. Define a model
public class User
{
    public int Id { get; set; }
    public string Name { get; set; }
}

// 2. Create a DbContext
public class AppDbContext : DbContext
{
    public AppDbContext(DbContextOptions<AppDbContext> options) : base(options) { }

    public DbSet<User> Users { get; set; }
}

// 3. Register the DbContext in Program.cs
// builder.Services.AddDbContext<AppDbContext>(options =>
//     options.UseSqlServer(builder.Configuration.GetConnectionString("DefaultConnection")));

// 4. Use it in a controller
public class UsersController : ControllerBase
{
    private readonly AppDbContext _context;
    public UsersController(AppDbContext context) { _context = context; }

    [HttpGet]
    public async Task<ActionResult<IEnumerable<User>>> GetUsers()
    {
        return await _context.Users.ToListAsync();
    }
}
# 6. Configuration
{
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft.AspNetCore": "Warning"
    }
  },
  "AllowedHosts": "*",
  "MyCustomSetting": "Hello from appsettings!"
}

// --- Accessing configuration in Program.cs ---
// var mySetting = builder.Configuration["MyCustomSetting"];

// --- Accessing via IConfiguration injection ---
public class MyService
{
    private readonly IConfiguration _config;
    public MyService(IConfiguration config)
    {
        _config = config;
        var mySetting = _config["MyCustomSetting"];
    }
}
master* 0 0