Skip to content
Tutorials Center
My learning

Topics

Lesson 50 of 52 ยท Practice and Review

Practice Exercises with Solutions

Twelve graded ASP.NET Core exercises on routing, middleware, dependency injection and authorization, each with a full, runnable solution you can check.

Reading about a framework teaches you the names of things. Writing code teaches you how they fit together. This page gives you twelve exercises, graded from easy to hard, across the four areas you use in every ASP.NET Core app: routing, middleware, dependency injection and configuration, and authentication with authorization. Every exercise has a full solution that runs on this page, so you can compare your own attempt with working code.

The exercises are split into three groups of four. Each group first states the tasks, then shows one runnable program that solves all four. Read the tasks, try them yourself in an empty editor, and only then press Run on the solution. If your output differs from the solution's, the difference usually teaches you something.

Cover the solution and write your own first, even if you only get half way. Struggling for ten minutes before you look builds far more skill than reading a perfect answer.

How to work

Each of your programs needs the same four lines of setup that every runnable example here uses: create the builder, clear the log providers, bind Kestrel to a free loopback port, and start with StartAsync so a client can call the app. If you need a refresher, revisit Your First Web App.

Grading:

  • Easy: one concept, a few lines.
  • Medium: two concepts working together.
  • Hard: needs you to read the framework's behavior carefully, not just copy a pattern.
flowchart LR
    A["Part 1<br/>Routing"] --> B["Part 2<br/>Middleware, DI, options"]
    B --> C["Part 3<br/>Auth and authorization"]

The three parts build on each other: routing first, then the pipeline and services, then security.

Part 1: routing and binding

Exercise 1 (easy): optional route parameter. Map GET /hello/{name?}. It returns Hello, <name>!, or Hello, stranger! when the name is missing. See route templates.

Exercise 2 (easy): route constraint. Map GET /products/{id} so id must be an integer of at least 1. Known ids (1 to 3) return a JSON object; an unknown id returns 404. What happens for /products/abc or /products/0?

Exercise 3 (medium): a route group. Under the prefix /api/v1/notes, map GET / (list all texts), POST / (add a note from a JSON body) and GET /{id}. The POST must answer 201 Created and set a Location header pointing at the new note. See route groups.

Exercise 4 (medium): query binding and validation. Map GET /search?q=...&limit=.... q is required (return a 400 validation problem when it is missing or blank). limit defaults to 5 and is clamped to the range 1 to 20. See parameter binding.

Now try them, then compare with this solution. The client at the bottom calls every route and prints the status code, the Location header when present, and the body.

C# Solutions to exercises 1-4

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

Things the output shows:

  • /products/abc and /products/0 both return 404, because the route constraint means the route does not match at all. The handler never runs.
  • Results.Created sets both the 201 status and the Location header.
  • Results.ValidationProblem produces the standard application/problem+json shape with an errors object.

If the output of your own version differs, check the order of the constraint (:int:min(1)) and whether you clamped limit after binding.

Part 2: middleware, dependency injection and options

Exercise 5 (easy): a request id. Write middleware that reads X-Request-Id from the request, or generates one (gen-1, gen-2, ...) when it is absent, and copies it to the response header of the same name. See writing custom middleware.

Exercise 6 (medium): a guard that short-circuits. Block every path under /admin with 403 Forbidden unless the request has the header X-Admin: yes. The endpoint behind it must never run for blocked requests. See the middleware pipeline.

Exercise 7 (medium): lifetimes. Register a scoped RequestCounter and a singleton VisitTotal. A middleware increments both once per request. The endpoint /counts increments the scoped counter again and returns both values. Predict the numbers over three calls before you run it. See dependency injection.

Exercise 8 (hard): the options pattern. Put Greeting:Text and Greeting:Repeat in in-memory configuration, bind them to a GreetingOptions class, and have /greeting return the text repeated Repeat times, separated by spaces. Do not read configuration directly in the handler. See configuration and options.

C# Solutions to exercises 5-8

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

What to notice:

  • The scoped counter is always 2: a new instance is created for every request, and the middleware and the endpoint share it within one request. The singleton keeps growing because one instance lives for the whole app. The earlier calls (three to /greeting, one allowed call to /admin/stats) also bumped the total, which is why the first /counts shows 5.
  • Middleware registered first runs first on the way in. The guard sits before the counting middleware, so a blocked request never bumps the counters.
  • Exercise 8's output (Howdy Howdy) appears in the request-id section, because /greeting is the endpoint those calls hit.

Part 3: authentication and authorization

For this part, every request carries an X-Api-Key header. Three keys exist: key-ann (user Ann, role user, age 30), key-bob (Bob, user, 15) and key-root (Root, admin, 40). Read authentication concepts if the handler pattern is new to you.

Exercise 9 (medium): an authentication handler. Write an AuthenticationHandler for the scheme ApiKey. No header means "anonymous" (no result); an unknown key fails; a known key produces a ClaimsPrincipal with name, role and an age claim. GET /me requires authentication and returns the user name. A missing key must give 401.

Exercise 10 (medium): role-based authorization. GET /admin requires the role admin. What status does Ann get? (Careful: not the same as the status for no key.)

Exercise 11 (hard): a policy. Add a policy named Adult that requires an age claim of at least 18, and protect GET /club with it. Bob (15) must be refused, Ann allowed. See authorization policies.

Exercise 12 (hard): resource-based authorization. PUT /notes/{id} is allowed only for the note's owner. The decision depends on the note itself, so it cannot be a simple attribute. Use IAuthorizationService with a requirement and a handler that receives the note.

C# Solutions to exercises 9-12

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

Read the status codes carefully, because this is where most people trip:

  • 401 Unauthorized means "I do not know who you are": no key, or a wrong key. The handler challenges.
  • 403 Forbidden means "I know who you are, and you may not do this": Ann on /admin, Bob on /club, Bob editing Ann's note. The handler forbids.
  • The resource-based check returns 404 for a missing note before asking whether the caller is allowed, which keeps the logic simple. Whether to hide a resource's existence from unauthorized callers (returning 404 instead of 403) is a design choice worth thinking about.

Going further

Once all twelve pass for you, stretch each one:

  • Exercise 3: reject an empty note with a problem details response.
  • Exercise 6: turn the guard into a reusable middleware class and register it with an extension method.
  • Exercise 7: provoke the captive dependency bug by injecting a scoped service into the singleton, and see what scope validation says.
  • Exercise 12: let admins edit any note by adding a second handler for the same requirement. (A requirement is met if any of its handlers succeeds.)

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. A request for /products/abc is mapped by /products/{id:int}. What happens?

    A failed route constraint means the route does not match at all, so routing returns 404 before any handler runs.
  2. 2. Which lifetime gives the same instance to the middleware and the endpoint of one request, but a new instance for the next request?

    A scope is created per request. Scoped services are shared inside that scope and discarded when the request ends.
  3. 3. Ann is signed in with a valid key, but the endpoint requires the admin role. What status should she get?

    She is authenticated, so the problem is permission, not identity. Authenticated but not allowed is 403.
  4. 4. How does a middleware stop the pipeline so that later components and the endpoint never run?

    Each middleware decides whether to call the next delegate. If it writes a response and returns without calling it, the request ends there.
  5. 5. Why is resource-based authorization done with IAuthorizationService instead of an attribute?

    An attribute is evaluated before the handler runs, with no access to the loaded resource. When the rule depends on that resource, you load it first and then ask the authorization service.

Summary

  • Route constraints decide whether a route matches; a failed constraint is a 404, not a handler error.
  • Route groups, Results.Created and Results.ValidationProblem cover most CRUD plumbing.
  • Middleware that does not call next short-circuits the pipeline; order decides what runs first.
  • Scoped services live for one request; singletons live for the app. Options bind configuration to typed classes.
  • 401 means unknown caller, 403 means known but not allowed.
  • Policies handle claim rules; resource-based authorization handles rules that need the loaded object.

Next: ASP.NET Core Interview Questions