Skip to content
Tutorials Center
My learning

Topics

Lesson 134 of 182 ยท ASP.NET Core

ASP.NET Core Overview

Meet ASP.NET Core - the app types (minimal APIs, MVC, Razor Pages, Blazor, SignalR, gRPC), Kestrel, WebApplication, the request pipeline - and run your first web server and call it with HttpClient.

ASP.NET Core is the framework for building web applications and HTTP services with C#. It powers public websites, mobile app back ends, internal APIs, real-time chat servers and microservices, and it is regularly among the fastest mainstream web frameworks in independent benchmarks. It is free, open source, cross-platform (Windows, Linux, macOS, containers) and part of every .NET SDK.

In the previous lessons you learned the building blocks it is made of: dependency injection, configuration, logging and the generic host. An ASP.NET Core app is a generic host that also runs a web server. So much of what you need is already familiar.

In this lesson you will get the big picture: which kinds of web apps exist, what Kestrel and the request pipeline are, what WebApplication gives you, and then you will start a real web server, inside one of our examples, and talk to it with HttpClient.

Our runner lets a program listen on the loopback address (127.0.0.1) and call itself with HttpClient. That is enough to learn everything about server code. You cannot open the page in a browser tab here; on your own machine you would run dotnet run and browse to the printed address.

What kinds of apps can you build?

ASP.NET Core is a family of related frameworks that share one foundation (hosting, middleware, routing, DI). You choose the style that fits your project:

Style What it is Typical use
Minimal APIs Endpoints declared with a few lines: app.MapGet("/hello", () => "Hi"). HTTP/JSON APIs, microservices, small sites. Covered in Minimal APIs.
MVC and Web API controllers Classes with action methods, attributes, filters, views. Large APIs and server-rendered sites with strong conventions.
Razor Pages A page = a .cshtml template plus a page model class. Server-rendered sites with forms.
Blazor Interactive UI written in C# and Razor, on the server (over SignalR) or in the browser (WebAssembly). Rich web apps without writing JavaScript.
SignalR Real-time messaging (WebSockets with fallbacks). Chat, live dashboards, notifications.
gRPC Binary, contract-first RPC over HTTP/2. Fast service-to-service calls.

They can live in one application: a Razor Pages site may also expose a minimal API and a SignalR hub. We take them in turn: Minimal APIs, routing and binding, middleware, and later MVC, Razor Pages and Blazor and SignalR and gRPC.

Kestrel: the web server inside your app

A web server is the program that listens on a network port, parses HTTP requests, and hands them to your code. In ASP.NET Core that server is Kestrel, a fast cross-platform server written in C# that runs inside your own process. There is no separate IIS or Apache required to run an app (though you can put a reverse proxy such as nginx, YARP, IIS or a cloud load balancer in front for TLS termination, compression, load balancing and static caching, which is the usual production setup).

Kestrel supports HTTP/1.1, HTTP/2 and HTTP/3, TLS, and WebSockets. Your app tells it where to listen with URLs, for example http://127.0.0.1:5000. Here is the smallest complete server you can write:

C# Your first web server

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 it line by line:

  1. WebApplication.CreateBuilder() creates the builder: DI container, configuration, logging and a web host, all with defaults (it is the web version of Host.CreateApplicationBuilder).
  2. builder.WebHost.UseUrls(...) chooses the address. In a real project the address normally comes from launchSettings.json, an environment variable such as ASPNETCORE_URLS, or the --urls option, and a plain dotnet run picks a free development port.
  3. builder.Build() freezes the service container and returns the WebApplication.
  4. app.MapGet("/", ...) declares an endpoint: when a GET request arrives for /, run this lambda and write its return value into the response.
  5. app.StartAsync() starts Kestrel in the background. In a real Program.cs you call app.Run() instead, which starts the server and blocks until shutdown (Ctrl+C), just like host.Run() in the previous lesson.
  6. HttpClient plays the browser. Afterwards we stop the server, which is what the runner needs so the program can exit.

In a real project you skip the address and the client. This is the whole Program.cs that dotnet new web creates (read-only, because it needs the dotnet CLI):

C#
var builder = WebApplication.CreateBuilder(args);
var app = builder.Build();

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

app.Run();

Four lines. WebApplication, MapGet and friends are available without any using thanks to the implicit usings of the web SDK (Microsoft.NET.Sdk.Web).

What happens to a request

When a browser or client sends a request, this is the journey:

  1. Kestrel accepts the TCP connection, decodes the HTTP bytes and builds an HttpContext: an object holding the Request, the Response, the user, the services and more.
  2. The HttpContext is passed through the middleware pipeline: a chain of components. Each one can look at or change the request, then call the next component, then act on the response on its way back. Typical middleware: exception handling, HTTPS redirection, static files, authentication, authorization, CORS.
  3. Near the end of the chain, routing decides which endpoint matches the URL and HTTP method, and the endpoint runs: your lambda, controller action or Razor page. Parameters are filled from the URL, query string, headers or body (model binding).
  4. The result is written to the response, flows back out through the middleware, and Kestrel sends it to the client.

You can see this chain by adding your own middleware with app.Use. Every call to next() goes deeper; code after it runs on the way back:

C# Watching a request travel through the pipeline

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.

The request goes down A, B, the endpoint; the response comes back up B, A. This "onion" shape is the single most important idea in ASP.NET Core. Middleware devotes a full lesson to it. For now just note that order matters: the first thing you register is the outermost layer.

WebApplication: both a builder and a router

WebApplication plays several roles at once, which explains why Program.cs is so short:

  • It implements IHost: it has Services, can Run/StartAsync/StopAsync, and has a lifetime.
  • It implements IApplicationBuilder: you add middleware with Use....
  • It implements IEndpointRouteBuilder: you add endpoints with Map....

And WebApplicationBuilder exposes everything you used before: builder.Services, builder.Configuration, builder.Logging, builder.Environment. The classic two-phase structure is worth memorising:

C#
// Phase 1: register services (configure the container)
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddSingleton<Clock>();
builder.Services.AddScoped<OrderService>();

// Phase 2: build, then configure the pipeline and endpoints
var app = builder.Build();
app.UseExceptionHandler("/error");
app.MapGet("/orders/{id}", (int id, OrderService orders) => orders.Find(id));

app.Run();

Services are registered before Build(); middleware and endpoints are added after. Once built, the container cannot change. Here is a version you can run, using a service in an endpoint:

C# Dependency injection in an endpoint

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.

Both responses show a scoped counter of 1. ASP.NET Core creates a new scope for every request, so a scoped service lives exactly as long as one request. A singleton like Greeter is shared across all requests, and a transient is created on every use. That is why you should keep scoped services (such as a database context) out of singletons.

For the first parameter, name, the framework looked at the route template and filled it from the URL. Parameters that are registered services are injected, and the rest is bound from the request (more in Routing and Model Binding).

Inside an endpoint: HttpContext, requests and responses

A lambda that returns a string produces a text/plain response with status 200. A returned object is serialised to JSON. When you need full control, you ask for HttpContext, HttpRequest or HttpResponse as parameters:

C# Reading the request, shaping the response

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.

Each line shows a different behavior: plain text is text/plain, an anonymous object becomes JSON with camelCase property names (the web default), Results.NoContent() gives 204 with no body, and a path nobody handles gives the framework's default 404 with an empty body. HttpContext also carries User (the authenticated identity), RequestServices (the per-request container) and RequestAborted (a cancellation token that fires when the client disconnects).

Configuration and environments

The builder reads configuration from the same sources you met in Configuration and Options: appsettings.json, appsettings.{Environment}.json, environment variables, and the command line. The environment name (Development, Staging, Production) selects extra files and behavior. In Development you typically enable detailed error pages; in Production you hide internals. It comes from ASPNETCORE_ENVIRONMENT, and the project templates set Development in launchSettings.json for dotnet run.

C#
if (app.Environment.IsDevelopment())
{
    app.UseDeveloperExceptionPage();
}
else
{
    app.UseExceptionHandler("/error");
    app.UseHsts();
}

Because the web host is a generic host, you can also run BackgroundService workers from the previous lesson in the same process as your web app (builder.Services.AddHostedService<...>()), and use the same ILogger<T> everywhere. Kestrel itself is registered as just another hosted service.

A tour of a real project

A new web project from the template (dotnet new web -o Shop) contains very little. This is what you would see on your machine (read-only, since it needs the dotnet CLI):

TEXT
Shop/
  Shop.csproj              <- project file: SDK, target framework
  Program.cs               <- the whole application
  appsettings.json         <- configuration, including logging levels
  appsettings.Development.json
  Properties/
    launchSettings.json    <- URLs and environment used by "dotnet run"
XML
<Project Sdk="Microsoft.NET.Sdk.Web">
  <PropertyGroup>
    <TargetFramework>net10.0</TargetFramework>
    <Nullable>enable</Nullable>
    <ImplicitUsings>enable</ImplicitUsings>
  </PropertyGroup>
</Project>

Microsoft.NET.Sdk.Web is the line that turns on ASP.NET Core: it references the whole shared framework (no NuGet packages needed for Kestrel, routing, minimal APIs, authentication, SignalR and so on) and enables the web implicit usings. You start the app with dotnet run or dotnet watch (which restarts on file changes), and publish it with dotnet publish (see Publishing and Deploying .NET Apps).

Pitfalls for newcomers

  • Order of middleware. Registering authentication after the endpoints, or exception handling last, simply does not work as expected. Read Middleware before building anything serious.
  • Singletons holding scoped data. A singleton cannot take a scoped dependency (the container throws in Development). Use IServiceScopeFactory, as shown for workers in The Generic Host.
  • Blocking calls. Request handling is asynchronous; blocking a thread with .Result or Thread.Sleep hurts throughput. Make endpoints async and await I/O.
  • Static mutable state. The app serves many requests at once on different threads. A plain List<T> field shared between requests will corrupt. Use thread-safe types, or a database.
  • Forgetting HTTPS in production. Kestrel serves plain HTTP unless configured; the usual setup terminates TLS at a proxy, and the app trusts forwarded headers.
  • Mixing up the two styles. Minimal APIs and controllers are different programming models. Pick one per feature area, not both for the same endpoint.

Which style should I choose?

For a new HTTP API, start with minimal APIs: less ceremony, very fast, and they scale to large projects when you organise them with route groups and extension methods (see the next lesson). Choose controllers when you want their conventions and filters or inherit an existing codebase. Choose Razor Pages for form-heavy server-rendered sites and Blazor when you want an interactive UI in C#. Because they share the same pipeline, you are not locking yourself in.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What is Kestrel?

    Kestrel listens on a port, parses HTTP and hands requests to the middleware pipeline. It is part of your own process, usually placed behind a reverse proxy in production.
  2. 2. In what order do two middleware components registered with app.Use (A first, then B) see a request and its response?

    Each middleware calls next() to go deeper. The request travels A, B, endpoint, and the response travels back B, A, like layers of an onion.
  3. 3. What does a scoped service's lifetime match in ASP.NET Core?

    The framework creates a new DI scope for each request and disposes it when the request ends.
  4. 4. Where do you register services and where do you add endpoints?

    Services are registered on builder.Services. Build() freezes the container; afterwards you configure the pipeline and endpoints on the WebApplication.
  5. 5. What does an endpoint lambda that returns an anonymous object produce by default?

    Returned objects are serialised to JSON (content type application/json) using System.Text.Json with web defaults such as camelCase names.

Summary

  • ASP.NET Core is a family of frameworks (minimal APIs, MVC, Razor Pages, Blazor, SignalR, gRPC) on one shared foundation of hosting, middleware, routing and DI.
  • Kestrel is the built-in web server; production setups usually put a reverse proxy in front.
  • A request becomes an HttpContext, travels through the middleware pipeline like an onion, reaches a routed endpoint and returns the same way.
  • WebApplication.CreateBuilder() gives you services, configuration, logging and environment; you register services before Build() and endpoints after it.
  • Scoped services live for one request; endpoints receive services, route values and HttpContext pieces as parameters.
  • In real projects dotnet run starts the app; in our examples StartAsync, HttpClient and StopAsync let you run a server and a client in one program.

Next: Minimal APIs