ASP.NET Core Exercises
Time to practise what you have learned. Most tasks below ask you to write real ASP.NET Core 9 code — try them in a local project created with dotnet new web, then compare with the solution. Three exercises are about the ideas underneath the framework and come with a runnable starter playground: replace the TODO parts, press ▶ Run and compare your output with the expected one.
Tip: There is never just one correct answer. If your endpoint returns the right status code and body, your solution is fine even if it looks different from ours.
Exercise 1: Hello with a name
Create a minimal API with two endpoints:
GET /helloreturns the plain textHello, stranger!GET /hello/{name}returnsHello, <name>!
Show solution
var builder = WebApplication.CreateBuilder(args);
var app = builder.Build();
app.MapGet("/hello", () => "Hello, stranger!");
app.MapGet("/hello/{name}", (string name) => quot;Hello, {name}!");
app.Run();Exercise 2: Paging with query parameters
Add GET /products that reads two optional query parameters, page (default 1) and size (default 10, maximum 50), and returns a JSON object such as {"page":2,"size":10,"skip":10}. Requests with page less than 1 should get 400 Bad Request.
Show solution
app.MapGet("/products", (int page = 1, int size = 10) =>
{
if (page < 1)
return Results.BadRequest(new { error = "page must be 1 or greater" });
size = Math.Clamp(size, 1, 50);
return Results.Ok(new { page, size, skip = (page - 1) * size });
});Optional parameters with default values are bound from the query string automatically. A request like /products?page=abc is rejected with 400 by the framework before your code even runs.
Exercise 3: Choosing the right result
Write GET /orders/{id:int} that returns 200 with the order when it exists, 404 when it does not, and declares both possibilities in its signature using TypedResults so they appear in the OpenAPI document. Use a dictionary as the data source.
Show solution
using Microsoft.AspNetCore.Http.HttpResults;
var orders = new Dictionary<int, Order>
{
[1] = new Order(1, "Keyboard", 49.90m),
[2] = new Order(2, "Monitor", 219.00m),
};
app.MapGet("/orders/{id:int}", Results<Ok<Order>, NotFound> (int id) =>
orders.TryGetValue(id, out var order)
? TypedResults.Ok(order)
: TypedResults.NotFound());
record Order(int Id, string Item, decimal Total);Exercise 4: Build a middleware chain by hand
Middleware is just a chain of functions where each one receives the next one. Complete the starter so that the request passes through a timing step, an auth check and finally the endpoint. The expected output is:
-> timer
-> auth
endpoint handles /reports
<- auth
<- timer
status: 200
-> timer
-> auth
<- timer
status: 401using System;
using System.Collections.Generic;
Func<Ctx, Action> endpoint = ctx => () =>
{
Console.WriteLine(quot;endpoint handles {ctx.Path}");
ctx.Status = 200;
};
// TODO: write a "timer" step and an "auth" step that wrap the next step.
// Requests without a user must stop in "auth" with status 401.
foreach (var ctx in new[] { new Ctx("/reports", "ana"), new Ctx("/reports", null) })
{
endpoint(ctx)();
Console.WriteLine(quot;status: {ctx.Status}");
}
class Ctx
{
public Ctx(string path, string user) { Path = path; User = user; }
public string Path { get; }
public string User { get; }
public int Status { get; set; }
}endpoint handles /reports
status: 200
endpoint handles /reports
status: 200
Show solution
using System;
foreach (var ctx in new[] { new Ctx("/reports", "ana"), new Ctx("/reports", null) })
{
Action<Ctx> endpoint = c =>
{
Console.WriteLine(quot;endpoint handles {c.Path}");
c.Status = 200;
};
Action<Ctx> auth = c =>
{
Console.WriteLine("-> auth");
if (c.User is null) { c.Status = 401; return; } // short-circuit
endpoint(c);
Console.WriteLine("<- auth");
};
Action<Ctx> timer = c =>
{
Console.WriteLine("-> timer");
auth(c);
Console.WriteLine("<- timer");
};
timer(ctx);
Console.WriteLine(quot;status: {ctx.Status}");
}
class Ctx
{
public Ctx(string path, string user) { Path = path; User = user; }
public string Path { get; }
public string User { get; }
public int Status { get; set; }
}In ASP.NET Core the same shape is written with app.Use(async (context, next) => { ...; await next(context); ... }).
Exercise 5: A request-id middleware
Write inline middleware that adds an X-Request-Id response header to every response. Use the value from the incoming X-Request-Id request header if present, otherwise context.TraceIdentifier.
Show solution
app.Use(async (context, next) =>
{
var id = context.Request.Headers["X-Request-Id"].FirstOrDefault()
?? context.TraceIdentifier;
context.Response.OnStarting(() =>
{
context.Response.Headers["X-Request-Id"] = id;
return Task.CompletedTask;
});
await next(context);
});OnStarting makes sure the header is added just before the response headers are sent, even if a later component starts writing the body.
Exercise 6: Pick the lifetime
For each service, choose AddSingleton, AddScoped or AddTransient and register it:
IClock— returns the current time, has no state.ShoppingCart— must be shared by everything that handles one request, but never between users.PriceCache— an in-memory cache shared by the whole app (thread-safe).
Show solution
builder.Services.AddSingleton<IClock, SystemClock>(); // stateless: one instance is fine (transient also works)
builder.Services.AddScoped<ShoppingCart>(); // one per HTTP request
builder.Services.AddSingleton<PriceCache>(); // shared for the app's lifetimeRemember the captive dependency rule: a singleton must not depend on a scoped service such as ShoppingCart or a DbContext.
Exercise 7: Strongly typed options
appsettings.json contains:
{
"Mail": { "Host": "smtp.example.com", "Port": 587, "From": "noreply@example.com" }
}Bind this section to a MailOptions class, validate that Host is required and Port is between 1 and 65535 at startup, and inject it into an endpoint GET /mail/settings that returns the host and port.
Show solution
using System.ComponentModel.DataAnnotations;
using Microsoft.Extensions.Options;
builder.Services.AddOptions<MailOptions>()
.BindConfiguration("Mail")
.ValidateDataAnnotations()
.ValidateOnStart();
// after builder.Build():
app.MapGet("/mail/settings", (IOptions<MailOptions> options) =>
new { options.Value.Host, options.Value.Port });
public class MailOptions
{
[Required] public string Host { get; set; } = "";
[Range(1, 65535)] public int Port { get; set; }
public string From { get; set; } = "";
}Exercise 8: Validate a request model
ASP.NET Core MVC validates [ApiController] models with Data Annotations. Annotate the SignUp class so the starter prints the expected errors, without changing the Main code:
alice: valid
(blank): The UserName field is required. | The Email field is not a valid e-mail address. | The field Age must be between 13 and 120.using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
var requests = new[]
{
new SignUp { UserName = "alice", Email = "alice@example.com", Age = 30 },
new SignUp { UserName = "", Email = "not-an-email", Age = 9 },
};
foreach (var r in requests)
{
var errors = new List<ValidationResult>();
bool ok = Validator.TryValidateObject(r, new ValidationContext(r), errors, validateAllProperties: true);
string who = r.UserName == "" ? "(blank)" : r.UserName;
Console.WriteLine(ok ? quot;{who}: valid" : quot;{who}: " + string.Join(" | ", errors.Select(e => e.ErrorMessage)));
}
class SignUp
{
// TODO: add [Required], [EmailAddress] and [Range] attributes
public string UserName { get; set; }
public string Email { get; set; }
public int Age { get; set; }
}alice: valid
(blank): valid
Show solution
class SignUp
{
[Required] public string UserName { get; set; }
[EmailAddress] public string Email { get; set; }
[Range(13, 120)] public int Age { get; set; }
}[Required] treats an empty string as missing, which is why the blank user name fails.
Exercise 9: Query an in-memory "DbSet"
EF Core translates LINQ into SQL, but the LINQ itself is the same you write against a list. Complete the query so it prints the three most expensive in-stock products per category, highest price first. Expected output:
Books: Clean Code (39.9), Refactoring (35.5)
Games: Chess Set (45), Puzzle (12)using System;
using System.Collections.Generic;
using System.Linq;
var products = new List<Product>
{
new(1, "Clean Code", "Books", 39.9m, 4),
new(2, "Refactoring", "Books", 35.5m, 2),
new(3, "Old Manual", "Books", 50m, 0),
new(4, "Chess Set", "Games", 45m, 7),
new(5, "Puzzle", "Games", 12m, 10),
};
// TODO: filter Stock > 0, group by Category, order and take the top 3 names
foreach (var p in products)
Console.WriteLine(quot;{p.Category}: {p.Name}");
record Product(int Id, string Name, string Category, decimal Price, int Stock);Books: Clean Code
Books: Refactoring
Books: Old Manual
Games: Chess Set
Games: Puzzle
Show solution
var report = products
.Where(p => p.Stock > 0)
.GroupBy(p => p.Category)
.OrderBy(g => g.Key)
.Select(g => quot;{g.Key}: " + string.Join(", ",
g.OrderByDescending(p => p.Price).Take(3).Select(p => quot;{p.Name} ({p.Price})")));
foreach (var line in report)
Console.WriteLine(line);With EF Core you would write the same query against db.Products and finish with await ...ToListAsync().
Exercise 10: An authorization policy
Protect DELETE /notes/{id} so that only authenticated users with the claim role = editor can call it. Define the policy once, by name, and apply it to the endpoint.
Show solution
builder.Services.AddAuthentication().AddJwtBearer();
builder.Services.AddAuthorizationBuilder()
.AddPolicy("Editors", policy => policy
.RequireAuthenticatedUser()
.RequireClaim("role", "editor"));
var app = builder.Build();
app.UseAuthentication();
app.UseAuthorization();
app.MapDelete("/notes/{id:int}", (int id) => TypedResults.NoContent())
.RequireAuthorization("Editors");Anonymous callers get 401 Unauthorized; signed-in users without the claim get 403 Forbidden.
Test yourself
In Exercise 2, what happens when a client calls /products?page=abc?
pagesilently becomes 1- The endpoint runs with
page = 0 - The framework returns 400 Bad Request before your handler runs
- The app crashes with an exception
Which lifetime fits a service that must be shared within one HTTP request but never across requests?
- Scoped
- Singleton
- Transient
- Static
A signed-in user without the required editor claim calls an endpoint protected by the Editors policy. What status code do they get?
- 401 Unauthorized
- 404 Not Found
- 400 Bad Request
- 403 Forbidden