Student learning series · Lesson 2 of 6
Create an ASP.NET Core API, return JSON, and understand route parameters and HTTP status codes.
What you will learn
An HTTP request contains a method and a path. An endpoint matches that pair and produces a response. A Minimal API maps routes directly to C# handlers. Start with GET before adding writes.
1. Create the project
dotnet new web -n RoutingLesson
cd RoutingLessonCreate a separate project for this lesson, then replace its Program.cs. Use the same steps for each later web lesson, changing the project name.
2. Complete Program.cs
var builder = WebApplication.CreateBuilder(args);
var app = builder.Build();
Student[] students = [new(1, "Asha"), new(2, "Ravi")];
app.MapGet("/", () => "Student API is running.");
app.MapGet("/students", () => students);
app.MapGet("/students/{id:int}", (int id) =>
{
var student = students.FirstOrDefault(s => s.Id == id);
return student is null ? Results.NotFound() : Results.Ok(student);
});
app.Run();
record Student(int Id, string Name);
3. Run and observe
dotnet run --no-launch-profile -- --urls http://127.0.0.1:5070Stop the server with Ctrl+C before starting the next lesson on the same port. For web lessons, visit the listed GET path at http://127.0.0.1:5070 in your browser. Use an HTTP client for POST, PUT and DELETE with Content-Type: application/json.
GET / returns Student API is running.
GET /students returns two student objects.
GET /students/1 returns Asha with status 200.
GET /students/99 returns status 404.4. Understand the code
CreateBuilder prepares hosting, configuration and services. Build creates the app. MapGet registers handlers and Run starts the server. The {id:int} route accepts an integer; a non-integer path does not match. Records describe data, and Results.Ok serializes the student as JSON.
Practice exercise
Add GET /students/count returning an object with a count property. Test IDs 1, 99 and a non-integer value.
Self-check and answer
The count is 2. ID 99 returns 404 because no student matches. A non-integer value fails the route constraint. A route constraint chooses routes; it is not business validation.
Study notes
Type the example yourself, run it, change one behavior, and explain the result in your own words. Keep each lesson in its own project. These examples were compiled with .NET SDK 9.0.306; select a currently supported SDK for new study projects. The course teaches modern .NET and ASP.NET Core, rather than obsolete .NET Core 3.1 or classic Web Forms.
Return to the .NET Core student learning path · Official Microsoft documentation · .NET support policy
No comments:
Post a Comment
Please do not enter any spam link in the comment box.