- Lab
-
Libraries: If you want this lab, consider one of these libraries.
ASP.NET Core Web API from Setup to Services
GearHub rents power tools to contractors and needs an internal Web API to track its equipment fleet. Each piece of equipment has a maintenance history (a parent-child relationship), a PDF manual that technicians download on site, and a photo uploaded when the equipment is checked in. The API must behave differently in Development (detailed errors and a larger upload limit) and Production (generic errors and a smaller upload limit). It relies on injected loggers and a manual/image storage service whose base path and upload limit come from environment-specific configuration. You’ll build this API step by step: first the pipeline, then the controllers, then error handling and downloads, and finally updates, JSON Patch, and image uploads.
Lab Info
Table of Contents
-
Challenge
Step 1: Explore the GearHub equipment API workspace
GearHub needs an equipment API
GearHub rents power tools to contractors, and every drill, saw, and generator in the fleet needs to be tracked: its rental status, the maintenance it has been through, the PDF manual technicians pull up on site, and the photo taken when it's checked back in. Over the next four steps you will grow a bare ASP.NET Core Web API into the service that does all of this, one file at a time. ## Tour the starter workspace
Open
src/and note the shape you'll be working in:Program.cswires up the builder, registers the repository and storage service, and calls intoPipelineConfiguratorbefore mapping controllers—you won't need to touch it.Models/Equipment.csholds the domain types: anEquipmentowns a list ofMaintenanceRecordentries, one per service visit.Models/Dtos.csholds the shapes the API actually sends and accepts:EquipmentDto,EquipmentCreateDto,EquipmentUpdateDto,MaintenanceRecordDto, andMaintenanceRecordCreateDto. The input DTOs already have the validation attributes Step 5 relies on.Repositories/IEquipmentRepository.csandRepositories/EquipmentRepository.csare an in-memory store that starts empty and assigns each new piece of equipment itsId; it's complete, and every controller you write calls into it.Controllers/EquipmentController.csandControllers/MaintenanceRecordController.csare the two routed controllers you'll fill in.Services/EquipmentMediaStorageService.cswill stream manuals and save uploaded photos once you finish it in steps 4 and 5. It readsMediaStorage:BasePathandMediaStorage:MaxImageSizeBytesfrom configuration.appsettings.Development.jsonandappsettings.Production.jsonlayer differentMediaStoragesettings on top ofappsettings.json—a bigger upload limit and a different base path inDevelopmentthan inProduction. That difference is the point: the API should behave differently per environment without any code branching on the environment name outside ofPipelineConfigurator. ## How the steps build on each other
Step 2 makes the request pipeline itself environment-aware and adds a logging middleware component. Step 3 completes the controller actions that list and create equipment and add maintenance records under it. Step 4 standardizes how errors and alternate formats look, and adds asynchronous manual downloads through an injected service. Step 5 closes the loop: validated updates, JSON Patch for partial edits, and a guarded photo upload that reuses the same storage service.
Each task's check is an automated test that calls the code you wrote. Some tests use an in-memory test server that sends real HTTP requests, so what you build has to actually behave correctly, not just compile. ## Before you start editing
Every task tells you exactly which file and method to change; the surrounding code already compiles and runs, so you're always completing behavior, not fixing broken scaffolding.
-
Challenge
Step 2: Configure the environment-aware request pipeline
Step 2: Configure the environment-aware request pipeline
ASP.NET Core builds its request pipeline as an ordered chain of middleware, and
IWebHostEnvironmentidentifies the current hosting environment, whether it's running inDevelopmentorProduction.src/PipelineConfigurator.csholds two static methods, called fromProgram.cs: one configures error handling for the environment, and the other maps a status endpoint. Right now, both methods contain placeholders. ## Reporting the active environmentBesides differing error behavior, the API needs a cheap way for anyone hitting it to confirm which environment answered. Minimal APIs let you map a route directly from
WebApplicationwithout a controller, which is exactly what a lightweight status check calls for. ## Writing your own middlewareThe middleware class you'll complete has a constructor that accepts the next delegate in the chain and an
InvokeAsync(HttpContext)method that returns aTask. ASP.NET Core invokes middleware in registration order.src/Middleware/RequestLoggingMiddleware.csalready has that shape wired into the pipeline, but its placeholder method doesn't yet forward, log, or measure requests. -
Challenge
Step 3: Design the Equipment and MaintenanceRecord controllers
Step 3: Design the
EquipmentandMaintenanceRecordcontrollersWhen returning equipment or maintenance data, you'll return DTOs rather than the
EquipmentorMaintenanceRecordentities themselves, so the wire format stays stable even if the domain model changes shape.EquipmentRepositoryis already implemented and injected into both controllers. You're wiring the HTTP surface on top of it, not the storage underneath it. It starts empty, so equipment exists only once a client creates it. ## Returning a precise201on createA REST
POSTthat creates a resource should answer with201 Created, aLocationheader pointing at the new resource, and the resource itself in the body.CreatedAtActionbuilds all three from an action name and route values in one call. ## Nesting a child resource under its parentA maintenance record only makes sense attached to one piece of equipment, so its routes live under
/api/equipment/{equipmentId}/maintenancerather than as a flat/api/maintenance.MaintenanceRecordControlleralready carries that route template - it just needs to check the parent exists before creating a child under it. -
Challenge
Step 4: Standardize errors, negotiate formats, and stream manuals
Step 4: Standardize errors, negotiate formats, and stream manuals
A client that asks for equipment that doesn't exist should get the same shape of error every time -
ProblemDetailsis the standard ASP.NET Core type for exactly that, carrying a status, a title, and a detail message as one JSON object instead of an ad hoc string. ## Letting clients ask for XML instead of JSONContent negotiation means the same action can answer in more than one format depending on the client's
Acceptheader. Adding the XML formatters to MVC's output pipeline is what makes anAccept: application/xmlrequest get XML back from an action that otherwise only ever produced JSON. ## Streaming a manual through an injected serviceEquipmentMediaStorageServiceis registered inProgram.csand injected wherever a controller needs it; its base path for manuals comes from theMediaStorage:BasePathsetting, which is different inappsettings.Development.jsonandappsettings.Production.json. Streaming the file asynchronously means the API starts sending bytes to the client before it has read the whole PDF into memory. -
Challenge
Step 5: Complete the equipment lifecycle with validation, patch, and upload
Step 5: Complete the equipment lifecycle with validation, patch, and upload
EquipmentUpdateDtoalready carries[Required]and[Range]attributes, and model validation records any violations inModelState. Because both controllers have[ApiController], MVC already answers an invalid request body with an automatic400before your action runs. That check lives in the MVC request pipeline, not in your action. It doesn't run when code calls the action method directly, as this task's unit test does, or whenSuppressModelStateInvalidFilteris enabled. An explicitModelState.IsValidguard lets your action reject errors already recorded inModelState; it doesn't run the validation attributes itself. ## Editing part of a resource with JSON PatchA
PUTreplaces a whole resource; aPATCHwith a JSON Patch document (application/json-patch+json) describes individual changes.JsonPatchDocument<EquipmentUpdateDto>.ApplyTomutates a DTO instance in place and records patch-operation errors inModelState, such as an attempt to update a property that doesn't exist. ## Guarding an upload before it touches diskAn upload endpoint that trusts the client's claimed content type or an unlimited size is one bad photo away from filling the disk or storing something that isn't an image.
MediaStorage:MaxImageSizeBytesin configuration sets that ceiling differently for Development and Production, andEquipmentMediaStorageServiceis where that limit and the content-type check both belong, since the upload controller action already delegates to it. -
Challenge
Step 6: Run the application
Every task is done, and each one was graded the moment you completed it. What you have not done yet is watch the whole application run at once—which is the only place the pieces you wrote separately become a single working program.
Start the application
Open the Terminal tab and run:
dotnet run --project src/Lab.csprojThe application runs in the Terminal and prints its hosting logs there. The pieces you wrote in the previous steps are now running together, but you'll need to send HTTP requests to see the endpoints in action.
Press Ctrl+C to stop the application before running the checks below. ### Run the checks yourself
The lab ran each task's test for you as you went, but they are ordinary tests and you can run them whenever you like. The whole suite:
dotnet test tests/Lab.Tests.csproj --nologo --verbosity quietOr one task at a time:
bash runTest.sh Task_2_1Each failing test's name identifies the task it belongs to, so the output tells you which step to go back to rather than which line to stare at. One thing worth trying before you finish: break something on purpose and watch the matching check fail, then put it back. Knowing what a failure looks like is worth as much as knowing what a pass looks like, and it costs you nothing here.
About the author
Real skill practice before real-world application
Hands-on Labs are real environments created by industry experts to help you learn. These environments help you gain knowledge and experience, practice without compromising your system, test without risk, destroy without fear, and let you learn from your mistakes. Hands-on Labs: practice your skills before delivering in the real world.
Learn by doing
Engage hands-on with the tools and technologies you’re learning. You pick the skill, we provide the credentials and environment.
Follow your guide
All labs have detailed instructions and objectives, guiding you through the learning process and ensuring you understand every step.
Turn time into mastery
On average, you retain 75% more of your learning if you take time to practice. Hands-on labs set you up for success to make those skills stick.